【发布时间】:2019-08-06 14:30:29
【问题描述】:
df 有
id measure t1 t2 t3
1 savings 1 2 5
1 income 10 15 14
1 misc 5 5 5
2 savings 3 6 12
2 income 4 20 80
2 misc 1 1 1
df 想要为每个 id 的度量添加一个新行,称为支出,通过减去 measure=income - measure=savings 来计算,对于每个 id 的每个时期 t1,t2,t3
id measure t1 t2 t3
1 savings 1 2 5
1 income 10 15 14
1 misc 5 5 5
1 spend 9 13 9
2 savings 3 6 12
2 income 4 20 80
2 misc 1 1 1
2 spend 1 14 68
尝试:
df.loc[df['Measure'] == 'spend'] =
df.loc[df['Measure'] == 'income']-
(df.loc[df['Measure'] == 'savings'])
失败是因为我没有合并 groupby 以获得期望的结果
【问题讨论】:
标签: python pandas dataframe sum difference