目前我有一个数据集,我试图在ColA为0时累积值,而当ColA再次变为1时,将值重置为0(重新开始计数)。
ColA 1 0 1 1 0 1 0 0 0 1 0 0 0
我的预期结果如下所示。
ColA Accumulate 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 2 0 3 1 0 0 1 0 2 0 3
我目前使用的代码如下
test['Value'] = np.where ( (test['ColA']==1),test['ColA'].cumsum() ,0)ColA Value 1 0 0 1 1 0 1 0 0 2 1 0 0 3 0 4 0 5 1 0 0 6 0 7 0 8
回答:
这样应该可以实现:
test['Value'] = (test['ColA']==0) * 1 * (test['ColA'].groupby((test['ColA'] != test['ColA'].shift()).cumsum()).cumcount() + 1)
这是对这个答案的改编。