Splitting a Column into Multiple Columns in Pandas
Pandas: Data Cleaning and Preprocessing Exercise-15 with Solution
Write a Pandas program to split a column into multiple columns.
This exercise demonstrates how to split a single column into multiple columns using str.split().
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame with combined data in one column
df = pd.DataFrame({
'Full_Name': ['Artair Mpho', 'Pompiliu Ukko', 'Gerry Sigismund']
})
# Split the 'Full_Name' column into 'First_Name' and 'Last_Name'
df[['First_Name', 'Last_Name']] = df['Full_Name'].str.split(' ', expand=True)
# Output the result
print(df)
Output:
Full_Name First_Name Last_Name 0 Artair Mpho Artair Mpho 1 Pompiliu Ukko Pompiliu Ukko 2 Gerry Sigismund Gerry Sigismund
Explanation:
- Created a DataFrame with full names combined into one column.
- Used str.split() to split the 'Full_Name' column into two new columns: 'First_Name' and 'Last_Name'.
- Returned the DataFrame with the separated name columns.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics