我正在努力使条件在达到之后持续下去。
我有这样的安排:
dft2 = pd.DataFrame([[True,1],[True,0],[True,1],[True,0],[True,1],[True,0],[False,1],[True,1],[True,1],[True,1]],columns = ['a','b'])
dft2['c'] = np.where(dft2['a']==True,dft2['b'],0)
dft2["cumc"] = dft2['c'].cumsum()
limit = 3现在,如果cumc达到了极限(实际上,这应该是绝对限制)。我想设置'cumc‘为零,把偏移到'c’。然后,我想将'cumc‘和'c’的所有行设置为零。
这在达到限制的行中实现了正确的行为,但在此后没有达到。
dft2["cumc"]=np.where(abs(dft2["c"].cumsum())==limit,0,dft2["c"].cumsum())
dft2['c']=np.where(abs(dft2["c"].cumsum())==limit,np.sign(dft2["c"].cumsum())*(abs(dft2["c"].cumsum())-1)*-1,dft2['c'])预期产出将是:
列'a‘和'b’不变,'c‘和'cumc’从第5行起为零
发布于 2020-11-04 12:30:31
您可以简单地找到累加和等于极限的行的索引,然后将后面的所有值赋值为零。
##look for the first index where the condition matches
index = dft2[dft2['cumc']==limit].index[0]
## assign all values after that to zero
dft2['c'].values[index:] = 0
dft2['cumc'].values[index:] = 0输出:
a b c cumc
0 True 1 1 1
1 True 0 0 1
2 True 1 1 2
3 True 0 0 2
4 True 1 0 0
5 True 0 0 0
6 False 1 0 0
7 True 1 0 0
8 True 1 0 0
9 True 1 0 0https://stackoverflow.com/questions/64679452
复制相似问题