首页 > 解决方案 > pandas cum 函数适用于有条件重置的行

问题描述

我有一个值为 0 或 1 的 pandas 列,例如。1, 1, 1, 0, 0, 1, 1, 0, ... 我想计算一个新列,在遇到 0 之前计算连续的 1,如果遇到 0,它将重置计数。

data = {'input': [0, 1, 1, 1, 1, 0, 0, 1, 1],  'expected output': [0, 1, 2, 3, 4, 0, 0, 1, 2]}
df = pd.DataFrame.from_dict(data)
df[['input',  'expected output']]

在此处输入图像描述

# logic
lst_in = [0, 1, 1, 1, 1, 0, 0, 1, 1]
lst_out = []        
lst_out.append(lst_in[0])      # lst_out 1st element is the same as the 1st element of lst_in
x_last = lst_in[0]
y_last = 0
for x in lst_in[1:]:
    if x_last == 0:     # reset 
        y = x
        y_last = y

    elif x_last == 1:   # cum current y
        if x == 1:
            y = x + y_last
        elif x == 0:    # reset next 
            y = 0

    x_last = x
    y_last = y
    #print(x_last, y_last)
    lst_out.append(y)

print(lst_out)

如果我先将其转换为列表,我可以使其工作。但是,我无法弄清楚如何使逻辑在熊猫框架下工作

标签: pythonpandas

解决方案


df.groupby(df['input'].eq(0).cumsum()).input.cumsum()

推荐阅读