【问题标题】:Counting rows since condition从条件开始计算行数
【发布时间】:2018-02-13 09:10:18
【问题描述】:
我在 Pandas 中有一个包含布尔值的列,并且想要计算自最后一个 True 值以来的行数,如下所示:
a b
False 0
True 0
False 1
False 2
False 3
True 0
False 1
True 0
我可以通过循环来做到这一点,但似乎必须有更好的方法
【问题讨论】:
标签:
python
pandas
boolean
cumsum
【解决方案1】:
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
【解决方案2】:
我发现上面的代码不起作用,但是这样做:
#Create DataFrame
import pandas as pd
d = {'condition': [False,False,False,True,False,False,True,False,True,False,False,False,False,False,False,True]}
df = pd.DataFrame(data=d)
#Calculate Rows Since Condition
df['counter'] = df.index.where(df.condition)
df['counter'].fillna(method="ffill",inplace=True)
df['Rows_since_condition'] = df.index-df['counter']
df.drop(['counter'], axis=1,inplace=True)
#Print Results
df
输出: