对 Pandas 中已分组的数据使用 groupby
我想使用 Pandas 在 Python 中实现以下结果。
我在 groupby
和 sum
上尝试过em>id 和 Group 列使用以下内容:
df.groupby(['id','Group'])['Total'].sum()
我得到了前两列,但我不确定如何获取第三列(Overall_Total) 。
我该怎么做呢?
初始数据(分组前)
id | 组 | 时间 |
---|---|---|
1 | a | 2 |
1 | a | 2 |
1 | a | 1 |
1 | b | 1 |
1 | b | 1 |
1 | c | 1 |
2 | e | 2 |
2 | a | 4 |
2 | e | 1 |
2 | a | 5 |
3 | c | 1 |
3 | e | 4 |
3 | a | 3 |
3 | e | 4 |
3 | a | 2 |
3 | 小时 | 4 |
I would like to achieve the result below in Python using Pandas.
I tried groupby
and sum
on the id and Group columns using the below:
df.groupby(['id','Group'])['Total'].sum()
I got the first two columns, but I'm not sure how to get the third column (Overall_Total).
How can I do it?
Initial data (before grouping)
id | Group | Time |
---|---|---|
1 | a | 2 |
1 | a | 2 |
1 | a | 1 |
1 | b | 1 |
1 | b | 1 |
1 | c | 1 |
2 | e | 2 |
2 | a | 4 |
2 | e | 1 |
2 | a | 5 |
3 | c | 1 |
3 | e | 4 |
3 | a | 3 |
3 | e | 4 |
3 | a | 2 |
3 | h | 4 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设 df 是您的初始数据框,请尝试以下操作:
Assuming
df
is your initial dataframe, please try this: