Reputation: 33
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
Upvotes: 0
Views: 157
Reputation: 33
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)
Upvotes: 1