【问题标题】:pandas row wise sum when when consecutive column value is less than a certain number当连续列值小于某个数字时,熊猫按行求和
【发布时间】:2020-06-29 15:30:27
【问题描述】:

我有一个这样的数据框,

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 循环执行此操作并将其与上一行进行比较,但执行时间会很长,需要寻找一些 pandas 快捷方式来最有效地执行此操作。

【问题讨论】:

标签: python pandas dataframe


【解决方案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

【讨论】:

  • col3 到 1,1,21,33,1,21?
猜你喜欢
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 2023-04-08
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
相关资源
最近更新 更多