我想知道如何获取具有多索引列的两行之间的差异比率,并将其存储在特定的列中。
我有一个看起来像这样的数据框。
>>>df
A B C
total diff total diff total diff
2020-08-15 100 0 200 0 20 0
每天,我都会添加一行。新行看起来像这样。
df_new
A B C
total diff total diff total diff
2020-08-16 200 - 50 - 30 -
对于列diff
,我想从上面的行中获取比率,作为的值total
。所以公式将是([total of today] - [total of the day before]) / [total of the day before]
A B C
total diff total diff total diff
2020-08-15 100 0 200 0 20 0
2020-08-16 200 1.0 50 -0.75 30 0.5
我知道如何添加新行。
day = dt.today()
df.loc[day.strftime("%Y-%m-%d"), :] = df_new.squeeze()
但是我不知道如何获得带有多索引列的两行之间的区别……任何帮助将不胜感激!谢谢。
使用shift
计算结果和更新原有DF:
s = df.filter(like="total").rename(columns={"total":"diff"}, level=1)
res = ((s - s.shift(1))/s.shift(1))
df.update(res)
print (df)
A B C
total diff total diff total diff
2020-08-15 100 0.0 200 0.00 20 0.0
2020-08-16 200 1.0 50 -0.75 30 0.5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句