在一系列行之间创建累积和

问题描述 投票:0回答:1
  • 第一列cond包含1或0
  • 第二列事件包含1或0
  • 我想创建第三列,其中每一行是两行之间COND列的累计和(cond%4的累计),其中event == 1(事件== 1的第一行必须包含在累积总和中但不包括最后一行)
+------+-------+--------+
| 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      |
+------+-------+--------+
python pandas
1个回答
1
投票

这可以通过pandas.groupby.transformcumsum轻松解决

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
© www.soinside.com 2019 - 2024. All rights reserved.