gpt4 book ai didi

python - 来自 groupby 的 Pandas 累积差异

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:08 36 4
gpt4 key购买 nike

我需要计算从 MultiIndex 级别开始的差异,以计算从级别开始的衰减。我的示例输入和输出将如下所示:

               values
place time
A a 120
b 100
c 90
d 50
B e 11
f 12
g 10
h 9

values

A a NaN
b -20
c -30
d -70
B e Nan
f +1
g -1
h -2

我可以使用 grouby 来获取关卡中连续单元格之间的差异:

df.groupby(level=0)['values'].diff()

但这不是我想要的!

唉,接受的答案不是我想要的。我有一个更好的例子:

arrays = [np.array(['bar', 'bar', 'bar', 'foo', 'foo', 'foo']),
np.array(['one', 'two', 'three', 'one', 'two', 'three'])]
df = pd.DataFrame([1000, 800, 500, 800, 400, 200], index=arrays)

bar one 1000
two 800
three 500
foo one 800
two 400
three 200

expected_result = pd.DataFrame([Nan, -200, -500, Nan, -400, -600], index=arrays)

bar one Nan
two -200
three -500
foo one Nan
two -400
three -600

但是 df.groupby(level=0).diff().cumsum() 的结果是:

pd.DataFrame([Nan, -200, -500, Nan, -900, -1100], index=arrays)

bar one Nan
two -200
three -500
foo one Nan
two -900
three -1100

最佳答案

你在寻找 cumsum 之后吗?

df.groupby(level=0)['values'].diff().cumsum()

关于python - 来自 groupby 的 Pandas 累积差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139128/

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