I would like to unlist one Pandas dataframe column into multiple columns in a chain. Like this, but ideally in a chain to help readability as there are more steps afterwards. Here is my example, which doesn't work.
d1 = {
'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']],
'bal':[5,7,8]
}
df2 = pd.DataFrame(d1)
#unlist teams column in chain
res=(df2
.pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
.assign(bal2=lambda x: x['bal']*2)
)
#final result like this
d3 = {
'team1': ['SF','SF','SF'],
'team2': ['NYG','NYG','NYG'],
'bal':[5,7,8],
'bal2':[10,14,16]
}
df4 = pd.DataFrame(d3)
CodePudding user response:
If use DataFrame.pop
for extract column and converting to DataFrame
then is possible add DataFrame.join
for append all another columns:
res= (pd.DataFrame(df2.pop('teams').to_list(), columns=['team1','team2'], index=df2.index)
.join(df2)
.assign(bal2 = lambda x: x['bal']*2))
print (res)
team1 team2 bal bal2
0 SF NYG 5 10
1 SF NYG 7 14
2 SF NYG 8 16