如何在满足另一列中的条件时重置 groupby cumsum?

How to reset a groupby cumsum when a condition in another column is met?

每次满足另一列中的条件时,我都会尝试将 cumsum 重置为零。这是我的数据框的样子:

ticker    cashflow op    shares profit
CPFE3.SA  -220.06  Buy    8          0
CPFE3.SA   249.93  Sell   0      29.87
CPFE3.SA   -90.03  Buy    3          0  
CPFE3.SA  -575.87  Buy    22         0
CPFE3.SA   -92.12  Buy    25         0
CPFE3.SA   763.52  Sell   0      35.37
DIS       -921.46  Buy    1          0

我正在使用以下内容创建利润列:

df['profit'] = df.groupby(df.ticker)['cashflow'].cumsum().where(df.op=='Sell',0)

Shares 是buying/selling之后我拥有的股票数量。利润是我想做的有点不同的东西。每次在 shares 列中遇到 0 时如何使 cumsum 重置?我尝试了一些东西,但我不喜欢这个。

我正在寻找的结果如下所示:

ticker    cashflow op    shares profit
CPFE3.SA  -220.06  Buy    8          0
CPFE3.SA   249.93  Sell   0      29.87
CPFE3.SA   -90.03  Buy    3          0  
CPFE3.SA  -575.87  Buy    22         0
CPFE3.SA   -92.12  Buy    25         0
CPFE3.SA   763.52  Sell   0        5.5
DIS       -921.46  Buy    1          0

在此先感谢,如果我可以提供更多信息,请告诉我。

您可以使用 cumsum 检测块:

#print to see what it does
blocks = df['shares'].eq(0)[::-1].cumsum()[::-1]

df['profit'] =(df.groupby(['ticker', blocks])
   ['cashflow'].cumsum()
   .where(df['shares'].eq(0),0)
)