对 Pandas 中已分组的数据使用 groupby

发布于 2025-01-14 14:43:59 字数 2678 浏览 0 评论 0原文

我想使用 Pandas 在 Python 中实现以下结果。

在此处输入图像描述

我在 groupbysum 上尝试过em>id 和 Group 列使用以下内容:

df.groupby(['id','Group'])['Total'].sum()

我得到了前两列,但我不确定如何获取第三列(Overall_Total) 。

我该怎么做呢?

初始数据(分组前)

id时间
1a2
1a2
1a1
1b1
1b1
1c1
2e2
2a4
2e1
2a5
3c1
3e4
3a3
3e4
3a2
3小时4

I would like to achieve the result below in Python using Pandas.

Enter image description here

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)

idGroupTime
1a2
1a2
1a1
1b1
1b1
1c1
2e2
2a4
2e1
2a5
3c1
3e4
3a3
3e4
3a2
3h4

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

べ映画 2025-01-21 14:43:59

假设 df 是您的初始数据框,请尝试以下操作:

df_group = df.groupby(['id','group']).sum(['time']).rename(columns={'time':'Total'})
df_group['All_total'] = df_group.groupby(['id'])['Total'].transform('sum')

Assuming df is your initial dataframe, please try this:

df_group = df.groupby(['id','group']).sum(['time']).rename(columns={'time':'Total'})
df_group['All_total'] = df_group.groupby(['id'])['Total'].transform('sum')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文