将cumsum
与交换的值一起使用,方法是将[::-1]
索引到传递给函数cumcount
的组:
df = pd.DataFrame({'failure': [0,0,0,1,0,0,1]})
s = df['failure'].iloc[::-1].cumsum()
df['time to failure'] = s.groupby(s).cumcount()
print (df)
failure time to failure
0 0 3
1 0 2
2 0 1
3 1 0
4 0 2
5 0 1
6 1 0