根据条件创建累积列pandas python

问题描述

我有多列的数据框。其中之一是累积生产。需要创建另一个名为“更正累积列”的列。请检查以下。

df:

enter image description here

我的方法

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

import pandas as pd
data = {'CummulativeProdution':[100,300,100,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()