我有一列0或1的值,例如1,1,1,0,0,1,1,0。。。 我想计算一个新列,在连续1遇到0之前对其进行计数,如果遇到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)
如果我先把它转换成列表,我就可以使它工作。然而,我不知道如何使逻辑在这个框架下工作
相关问题 更多 >
编程相关推荐