gpt4 book ai didi

python - 如何根据另一列添加到 Pandas 列

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:33 25 4
gpt4 key购买 nike

目前我有一个看起来像这样的表

ID       Previous_Injuries    Currently_Injured      Injury_Type
1 Nan 0 Nan
1 Nan 1 Ankle
1 Nan 0 Nan
1 Nan 1 Wrist
1 Nan 0 Nan
1 Nan 1 Leg
1 Nan 0 Nan
2 Nan 1 Leg
2 Nan 0 Nan

我想添加到以前的伤害列并使我的表格看起来像这样:

ID       Previous_Injuries    Currently_Injured      Injury_Type
1 Nan 0 Nan
1 Nan 1 Ankle
1 [Ankle] 0 Nan
1 [Ankle] 1 Wrist
1 [Ankle,Wrist] 0 Nan
1 [Ankle,Wrist] 1 Leg
1 [Ankle,Wrist,Leg] 0 Nan
2 Nan 1 Leg
2 [Leg] 0 Nan

如何在 pandas 中实现这种专栏?最好以列表的形式来做吗?

谢谢!

最佳答案

我们可以用cumsumshift,然后split字符串,注意这里你使用的是Nan (string type) ,不是np.nan

s=df.Injury_Type.shift().fillna('Nan').add(',').cumsum().str[:-1].str.split(',')
df['new']=[[y for y in x if y != 'Nan'] for x in s ]
df
Out[322]:
ID Previous_Injuries Currently_Injured Injury_Type new
0 1 Nan 0 Nan []
1 1 Nan 1 Ankle []
2 1 Nan 0 Nan [Ankle]
3 1 Nan 1 Wrist [Ankle]
4 1 Nan 0 Nan [Ankle, Wrist]
5 1 Nan 1 Leg [Ankle, Wrist]
6 1 Nan 0 Nan [Ankle, Wrist, Leg]

再换题!

l=[]
for name , dfx in df.groupby('ID'):
s = dfx.Injury_Type.shift().fillna('Nan').add(',').cumsum().str[:-1].str.split(',')
dfx['new'] = [[y for y in x if y != 'Nan'] for x in s]
l.append(dfx)

pd.concat(l)

关于python - 如何根据另一列添加到 Pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com