我有一个值为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)
如果我先将其转换为列表,就可以进行工作。但是,我无法弄清楚如何使逻辑在pandas框架下工作
答案 0 :(得分:1)
df.groupby(df['input'].eq(0).cumsum()).input.cumsum()