根据条件创建累积列 pandas python

create cumulative column based on conditions pandas python

我有包含多列的数据框。其中之一是 CumulativeProduction。需要创建另一个名为 'corrected Cummulative Column' 的列。请检查下面。

df:

我的做法:

我尝试使用前向填充来填充 0,但如果该列具有多组值(例如下面部分中的 100,200,300),它就会失败。有办法解决这个问题吗?

import pandas as pd
data = {'CummulativeProdution':[100,200,300,0,0,0,100,200,300,0,0,0]      
       }

df = pd.DataFrame(data)

您可能需要 运行 cumsum() 从第一个零之前的值开始:

df['Corrected'] = df['CummulativeProdution']

mask = df['CummulativeProdution'] == 0

# if the series has zeros
if mask.any():
    # find the index of the first zero
    first_zero_idx = df[mask].index[0]
    # assuming monotonic increasing index
    before_zero_idx = first_zero_idx - 1
    df.loc[before_zero_idx:, 'Corrected'] = df.loc[before_zero_idx:, 'Corrected'].cumsum()