0

A similar question has been answered here Pandas split column of lists into multiple columns

However, the solution can only apply to a single column of list, how about if I have multiple columns of lists, is there any better ways to splitting those columns instead of using the solution above to break down the column one by one?

For example

df = pd.DataFrame({"teams": [["SF", "NYG"] for _ in range(7)], "cities": [["NY", "LA"] for _ in range(7)]})

    teams       cities
0   [SF, NYG]   [NY, LA]
1   [SF, NYG]   [NY, LA]
2   [SF, NYG]   [NY, LA]
3   [SF, NYG]   [NY, LA]
4   [SF, NYG]   [NY, LA]
5   [SF, NYG]   [NY, LA]
6   [SF, NYG]   [NY, LA]

to

  team1 team2 city1 city2
0    SF   NYG    NY   LA
1    SF   NYG    NY   LA
2    SF   NYG    NY   LA
3    SF   NYG    NY   LA
4    SF   NYG    NY   LA
5    SF   NYG    NY   LA
6    SF   NYG    NY   LA

Thanks in advance

1 Answer 1

1

I found a solution while writing this question,

splits = [pd.DataFrame(df[col].tolist()).add_prefix(col) for col in df.columns]
clean_df = pd.concat(splits, axis=1)
Sign up to request clarification or add additional context in comments.

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.