我需要计算多重索引级别的起始差异,以计算级别开始时的衰减。我的示例输入和输出将如下所示:
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
我可以使用groupby函数来获取同一层级中相邻单元格之间的差异:
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