Python- pandas -展开/删除累计金额 [英] Python - Pandas - Unroll / Remove Cumulative Sum
本文介绍了Python- pandas -展开/删除累计金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似以下的数据框(下面是特定数据,这是通用的).否会给我累计的金额:
I have a data frame like the following (specific data below, this is generic). The no gives me a cumulative sum:
no
name day
Jack Monday 10
Tuesday 40
Wednesday 90
Jill Monday 40
Wednesday 150
我想累计"累计金额,以便给我这样的信息:
I want to "unroll" the cumulative sum to give me something like this:
print df
name day no
0 Jack Monday 10
1 Jack Tuesday 30
2 Jack Wednesday 50
3 Jill Monday 40
4 Jill Wednesday 110
本质上,我想执行以下操作,但相反: 熊猫groupby累积总和
In essence, I'd like to do something like the following, but in reverse: Pandas groupby cumulative sum
推荐答案
如果我正确理解,则可以执行以下操作:
If I understand correctly you can do the following:
In [103]:
df.groupby(level=0).diff().fillna(df).reset_index()
Out[103]:
name day no
0 Jack Monday 10.0
1 Jack Tuesday 30.0
2 Jack Wednesday 50.0
3 Jill Monday 40.0
4 Jill Wednesday 110.0
因此groupby
是第一个索引级别,然后调用diff
来计算每组的行间差异,并用原始df值填充NaN
值,然后调用reset_index
So groupby
the first index level and call diff
to calculate the inter row differences per group and fill the NaN
values with the original df values and call reset_index
这篇关于Python- pandas -展开/删除累计金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文