How to Split Values in a Column in Pandas A Comprehensive Guide

To split values in a column in Pandas, you can use the str.split() method. This method splits a string into a list of substrings based on a specified separator.

Here is an example of how to split values in a Pandas DataFrame column:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'Name': ['John Smith', 'Jane Doe', 'Bob Johnson'],
                   'Age': [30, 25, 40],
                   'City, State': ['New York, NY', 'Los Angeles, CA', 'Chicago, IL']})

# Split the 'City, State' column into two separate columns
df[['City', 'State']] = df['City, State'].str.split(', ', expand=True)

# Drop the original 'City, State' column
df = df.drop('City, State', axis=1)

# Print the updated DataFrame
print(df)

Output:

          Name  Age         City State
0   John Smith   30     New York    NY
1     Jane Doe   25  Los Angeles    CA
2  Bob Johnson   40      Chicago    IL

In this example, the str.split() method is used to split the ‘City, State’ column into two separate columns, ‘City’ and ‘State’, using ‘, ‘ as the separator. The expand=True argument tells Pandas to return a DataFrame with one column for each substring. Finally, the original ‘City, State’ column is dropped using the drop() method with axis=1.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *