1

I am new to this, and I need to split a column that contains two strings into 2 columns, like this:

Initial dataframe:

    Full String
0   Orange Juice
1   Pink Bird
2   Blue Ball
3   Green Tea
4   Yellow Sun

Final dataframe:

    First String    Second String
0   Orange           Juice
1   Pink             Bird
2   Blue             Ball
3   Green            Tea
4   Yellow           Sun

I tried this but doesn't work:

df['First String'] , df['Second String'] = df['Full String'].str.split()

and this:

df['First String', 'Second String'] = df['Full String'].str.split()

How to make it work? Thank you!!!

Andrew Tulip
  • 161
  • 6

2 Answers2

6

The key here is to include the parameter expand=True in your str.split() to expand the split strings into separate columns.

Type it like this:

df[['First String','Second String']] = df['Full String'].str.split(expand=True)

Output:

    Full String First String Second String
0  Orange Juice       Orange         Juice
1     Pink Bird         Pink          Bird
2     Blue Ball         Blue          Ball
3     Green Tea        Green           Tea
4    Yellow Sun       Yellow           Sun
sophocles
  • 13,593
  • 3
  • 14
  • 33
0

have you tried this solution ?

https://stackoverflow.com/a/14745484/15320403

df = pd.DataFrame(df['Full String'].str.split(' ',1).tolist(), columns = ['First String', 'Second String'])

Netim
  • 135
  • 7