Consider a Pandas DataFrame with a column containing lists:
import pandas as pd df = pd.DataFrame({"teams": [[["SF", "NYG"]] for _ in range(7)]}) teams 0 [[SF, NYG]] 1 [[SF, NYG]] 2 [[SF, NYG]] 3 [[SF, NYG]] 4 [[SF, NYG]] 5 [[SF, NYG]] 6 [[SF, NYG]]
To transform this column into two individual columns, follow the below steps:
import pandas as pd d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'], ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]} df2 = pd.DataFrame(d1) print (df2) teams 0 [SF, NYG] 1 [SF, NYG] 2 [SF, NYG] 3 [SF, NYG] 4 [SF, NYG] 5 [SF, NYG] 6 [SF, NYG]
Assign a new DataFrame with the desired columns:
df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index) print (df2) teams team1 team2 0 [SF, NYG] SF NYG 1 [SF, NYG] SF NYG 2 [SF, NYG] SF NYG 3 [SF, NYG] SF NYG 4 [SF, NYG] SF NYG 5 [SF, NYG] SF NYG 6 [SF, NYG] SF NYG
Alternatively, a new DataFrame can be created separately:
df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2']) print (df3) team1 team2 0 SF NYG 1 SF NYG 2 SF NYG 3 SF NYG 4 SF NYG 5 SF NYG 6 SF NYG
Note: Using apply(pd.Series) for this operation can be significantly slower than the methods described above.
The above is the detailed content of How to Split a Pandas Column of Lists into Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!