如何从基于年期间的前面的另一列行中减去一列行的值?

How can I subtract values of one column rows from another column row which is preceding on the basis of Year period?

我有一个 table,其中有多个专栏,但我只会提及那些关注焦点的栏目。

Year Current Amount Previous Amount Type
2021 22000 36000 C5 70
2022 26000 48000 C4 68
2023 76440 34000 C5 70
2024 21399 12000 C4 68
2024 22000 11000 C4 34
2024 26500 13000 C4 23
2025 16000 34000 C4 68
2025 76000 22000 C4 34
2025 34000 64000 C4 23

现在显然有许多年份值的方法。我想要的是假设年份为 2022 年时从以前的金额中减去当前金额值,当年份为 2021 年时,简单地说,从以前的金额中减去当前金额,其中以前金额的每年值都高于默认值。例如,我希望结果看起来像这样。

Year Current Amount Previous Amount Type Change
2021 22000 36000 C5 70 Nan
2022 26000 48000 C4 68 -10,000
2023 76440 34000 C5 70 28,440
2024 21399 12000 C4 68 35899
2024 22000 11000 C4 34 35899
2024 26500 13000 C4 23 35899
2025 16000 34000 C4 68 90000
2025 76000 22000 C4 34 90000
2025 34000 64000 C4 23 90000

我试过使用以下代码,但到目前为止没有成功:

Df['Current Amount'] - Df['Previous Amount'].where(Df['Year']==Df['Year']-1)

另外:

Df['Current Amount'] - Df['Previous Amount'].where(Df['Year']==Df['Year'].shift(-1))

请帮帮我。提前致谢。

重复数据

# aggregate data
df2 = df.groupby('Year')[['Current Amount', 'Previous Amount']].sum()
# ensure having all intermediate years
df2 = df2.reindex(range(df2.index.min(), df2.index.max()+1))

# compute the change and merge
df.merge(df2['Current Amount'].sub(df2['Previous Amount'].shift()).rename('Change'),
         on='Year', how='left')

输出:

   Year  Current Amount  Previous Amount   Type   Change
0  2021           22000            36000  C5 70      NaN
1  2022           26000            48000  C4 68 -10000.0
2  2023           76440            34000  C5 70  28440.0
3  2024           21399            12000  C4 68  35899.0
4  2024           22000            11000  C4 34  35899.0
5  2024           26500            13000  C4 23  35899.0
6  2025           16000            34000  C4 68  90000.0
7  2025           76000            22000  C4 34  90000.0
8  2025           34000            64000  C4 23  90000.0

较早的回答

IIUC,假设连续年份,使用:

df['Change'] = df['Current Amount'].sub(df['Previous Amount'].shift())

或者,要确保映射前一年,请使用:

s = df.set_index('Year')['Previous Amount']
s.index += 1

df['Change'] = df['Current Amount'].sub(df['Year'].map(s))

输出:

   Year  Current Amount  Previous Amount   Type   Change
0  2021           22000            36000  C5 70      NaN
1  2022           26000            48000  C4 68 -10000.0
2  2023           76440            34000  C5 70  28440.0
3  2024           21399            12000  C4 68 -12601.0