Pandas 取消列出链中的一个数据框列
Pandas unlist one dataframe column in chain
我想取消列出一个 Pandas 数据框列到链中的多个列中。像 ,但最好是在一个链中以帮助提高可读性,因为之后有更多的步骤。这是我的例子,它不起作用。
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)
如果使用 DataFrame.pop
for extract column and converting to DataFrame
then is possible add DataFrame.join
附加所有其他列:
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
我想取消列出一个 Pandas 数据框列到链中的多个列中。像
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)
如果使用 DataFrame.pop
for extract column and converting to DataFrame
then is possible add DataFrame.join
附加所有其他列:
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