基于其他列 Python 3+ Pandas 数据框条件的年度累积总和

Year wise cumsum based on condition on other column Python 3+ Pandas data frame

我有一个包含三列的数据框:年份、价格、PV。如果 Price 列中的值不等于零,我希望列 PV 的累计总和根据 Year 列重置。

df = pd.DataFrame({"Year": [2000] * 3 + [2001] * 3,
                   "Value": [0,100,0,0,100,100],
                   "PV": [7,8,9,12,13,14],
                   'Cumsum':[0,15,0,0,25,39]})

print (df)
   Year  Value  PV  Cumsum
0  2000      0   7       0
1  2000    100   8      15
2  2000      0   9       0
3  2001      0  12       0
4  2001    100  13      25
5  2001    100  14      39

使用numpy.where with DataFrameGroupBy.cumsum:

df['Cumsum'] = np.where(df['Value'] == 0, 0, df.groupby('Year')['PV'].cumsum())
print (df)
   Year  Value  PV  Cumsum
0  2000      0   7       0
1  2000    100   8      15
2  2000      0   9       0
3  2001      0  12       0
4  2001    100  13      25
5  2001    100  14      39