How to split a DataFrame string column into two columns?

Given a DataFrame, we have to split its string column into two columns.
Submitted by Pranit Sharma, on May 17, 2022

A string is a group of characters. A string can contains any type of character including numerical characters, alphabetical characters, special characters, etc. Splitting a string means distributing a string in two or more parts. By default, a string is split with a space between two words but if we want to split a string with any other character, we need to pass the specific character inside str.split() method. Here, for splitting a string into two different columns, we are going to use str.split() method.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example.

# Importing pandas package
import pandas as pd

# Creating a Dictionary
dict = {
    'Name':['Amit Sharma','Bhairav Pandey','Chirag Bharadwaj','Divyansh Chaturvedi','Esha Dubey'],

# Creating a DataFrame
df = pd.DataFrame(dict)

# Display DataFrame

# Spliting Column "Name" into two columns 
# first name and last name
df[['First','Last']] = df.Name.str.split(expand=True)

# Display modified DataFrame:
print("Modified DataFrame:\n",df)


Example: Split a DataFrame string column into two columns

Python Pandas Programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.