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!!!

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It works! I will accept the answer in 9 minutes
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'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.