w3resource

Splitting a Column into Multiple Columns in Pandas


15. Splitting a Column into Multiple Columns

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to split a column containing full names into separate columns for first name, middle name, and last name.
  • Write a Pandas program to split a column with dates in 'YYYY-MM-DD' format into separate year, month, and day columns.
  • Write a Pandas program to split a column containing delimited strings into multiple columns and then drop the original column.
  • Write a Pandas program to split a column containing addresses into separate columns for street, city, state, and zip code based on comma delimiters.

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.



Follow us on Facebook and Twitter for latest update.