+------+-------+--------+ | cond | event | Result | +------+-------+--------+ | 0 | 0 | 0 | | 1 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 1 | | 1 | 0 | 2 | | 0 | 0 | 2 | | 1 | 0 | 3 | | 1 | 0 | 0 | | 1 | 0 | 1 | | 1 | 0 | 2 | | 1 | 1 | 1 | +------+-------+--------+
答案 0 :(得分:1)
这可以通过pandas.groupby.transform
和cumsum
event_cum = df['event'].cumsum()
result = df['cond'].groupby(event_cum).transform('cumsum').mod(4)
result[event_cum == 0] = 0 # rows before the first event
0 0 1 0 2 0 3 1 4 2 5 2 6 3 7 0 8 1 9 2 10 1 Name: cond, dtype: int64