如何将Groupby与原始DataFrame合并?

发布于 2025-01-29 20:57:59 字数 404 浏览 2 评论 0原文

我有一个带有32列的数据框,类似的内容是:

    company_id       Price           Date     others columns
       10           258.33        2021-08-01    ...
       11           300.00        2022-01-01    ...
       12           760.82        2021-11-01    ...

我想要公司和一个月的组:

df.groupby(['company_id', 'Date']).sum()

这很好,但是如何将输出与上面的初始数据框架合并?喜欢所有的行。会有双龙,但很好。

I have a dataframe with 32 columns, something like that :

    company_id       Price           Date     others columns
       10           258.33        2021-08-01    ...
       11           300.00        2022-01-01    ...
       12           760.82        2021-11-01    ...

I want a groupby by company and by month :

df.groupby(['company_id', 'Date']).sum()

This works perfectly fine but how to merge the output with my initial dataframe above ? Like for all the rows. There will be doublons but it's fine.

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

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

发布评论

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

评论(1

她比我温柔 2025-02-05 20:57:59

IUUC,您想要的是Groupby,并转换

out = (df.groupby(['company_id', 'Date'])
       .transform(sum)
       .rename(columns=lambda col: f'{col}_sum'))
out = df.join(out)
print(out)

   company_id   Price        Date  Price_sum
0          10  258.33  2021-08-01     258.33
1          11  300.00  2022-01-01     300.00
2          12  760.82  2021-11-01     760.82

IUUC, what you want is groupby and transform

out = (df.groupby(['company_id', 'Date'])
       .transform(sum)
       .rename(columns=lambda col: f'{col}_sum'))
out = df.join(out)
print(out)

   company_id   Price        Date  Price_sum
0          10  258.33  2021-08-01     258.33
1          11  300.00  2022-01-01     300.00
2          12  760.82  2021-11-01     760.82
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文