总和/标记之间的行的平均值在数据帧中切换 [英] Sum / Mean of the rows between the flags toggle in dataframe

查看:64
本文介绍了总和/标记之间的行的平均值在数据帧中切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框

id  power   flag
0   20      0
1   25      0
2   26      1
3   30      1
4   18      0
5   30      0
6   19      0
7   21      1
8   23      0

我正在尝试获取 power 列的均值/总和 输出应该像这样

I am trying to get the mean /sum of rows of power column the output should look like this

0   45 (20 +25)
1   56 (26 + 30)
2   67 (18 +30 +19)
3   21 (21)
4   23 (23)

如果这些标志不是二进制怎么办?

Also what if the flags are not binary?

有人可以帮我吗?谢谢

推荐答案

IIUC,使用diff.ne(0)中的布尔值的累积和作为分组器,而只是sum

IIUC, use the cumulative sum of boolean values from diff.ne(0) as grouper, and just sum

df.groupby(df.flag.diff().ne(0).cumsum()).power.sum()


flag
1    45
2    56
3    67
4    21
5    23
Name: power, dtype: int64

这篇关于总和/标记之间的行的平均值在数据帧中切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆