连续列值小于一定数时的熊猫行和

时间:2020-06-29 15:30:27

标签: python pandas dataframe

我有一个这样的数据框,

df
col1     col2    col3
 A       34       1
 B       86       2
 A       53       21
 C       24       33
 B       21       2
 C       11       1

现在,我想逐行添加col1和col2值,其中连续的col3值小于3,因此最终数据帧看起来像这样,

 col1    col2
   A      120
   A       53
   C       24
   B       32

我可以使用for循环并将其与上一行进行比较,但是执行时间会很长,需要一些熊猫快捷方式来最有效地执行此操作。

1 个答案:

答案 0 :(得分:1)

您可以使用cumsum获取值<=3的连续块:

s = df.col3.ge(3)

# print `s.cumsum()` and `s` to see details
df.groupby([s.cumsum(),s], as_index=False).agg({'col1':'first','col2':'sum'})

输出:

  col1  col2
0    A   120
1    A    53
2    B    32
3    C    24