Q:

How to split a DataFrame string column into two columns?

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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'],
    'Age':[20,20,19,21,18]
}

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

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

# 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)

Output:

Example: Split a DataFrame string column into two columns

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to add x and y labels to a pandas plot?... >>
<< How to obtain the element-wise logical NOT of a Pa...