Python 达到极限后使条件持续
我正在努力使条件在达到后保持不变 我有这样的设置:Python 达到极限后使条件持续,python,pandas,Python,Pandas,我正在努力使条件在达到后保持不变 我有这样的设置: 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'].cums
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达到极限(实际上这应该是绝对极限)。我想通过将偏移量设置为“c”,将“cumc”设置为零。然后我想将“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行开始为零您只需找到该行的索引,其中累积和等于限制,然后将该行之后的所有值分配为零
##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 0
谢谢,非常简单,很好的解决方案。但它假设极限实际上是序列的一部分。如果不是,它会返回一个错误。你所说的限制实际上是这个系列的一部分是什么意思?逻辑上,它应该出现在它里面,对吗?不,它不是,它是一个上限,可能高于cumcIf中的所有数字,就是这样,那么为什么不在开头放一个if语句来检查它是否更小,并进行修改呢。