我在 Pandas 中有一列包含 boolean 值,我想计算自最后一个 True 值以来的所有行,如下所示:
a b
False 0
True 0
False 1
False 2
False 3
True 0
False 1
True 0
我可以通过循环来完成,但似乎必须有更好的方法
最佳答案
a = ~df['a']
b = a.cumsum()
c = b-b.where(~a).ffill().fillna(1).astype(int)
print (c)
0 0
1 0
2 1
3 2
4 3
5 0
6 1
7 0
Name: a, dtype: int32
关于python - 从条件开始计算行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46048747/