每次出现0时重置的Python pandas cumsum [英] Python pandas cumsum with reset everytime there is a 0
本文介绍了每次出现0时重置的Python pandas cumsum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个0和1的矩阵,并且想对每列进行一次累加,每当观察到零时就将其重置为0.例如,如果我们有以下内容:
I have a matrix with 0s and 1s, and want to do a cumsum on each column that resets to 0 whenever a zero is observed. For example, if we have the following:
df = pd.DataFrame([[0,1],[1,1],[0,1],[1,0],[1,1],[0,1]],columns = ['a','b'])
print(df)
a b
0 0 1
1 1 1
2 0 1
3 1 0
4 1 1
5 0 1
我想要的结果是:
print(df)
a b
0 0 1
1 1 2
2 0 3
3 1 0
4 2 1
5 0 2
但是,当我尝试df.cumsum() * df
时,我能够正确识别0个元素,但计数器不会重置:
However, when I try df.cumsum() * df
, I am able to correctly identify the 0 elements, but the counter does not reset:
print(df.cumsum() * df)
a b
0 0 1
1 1 2
2 0 3
3 2 0
4 3 4
5 0 5
推荐答案
您可以使用:
a = df != 0
df1 = a.cumsum()-a.cumsum().where(~a).ffill().fillna(0).astype(int)
print (df1)
a b
0 0 1
1 1 2
2 0 3
3 1 0
4 2 1
5 0 2
这篇关于每次出现0时重置的Python pandas cumsum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文