python groupby计算比率

发布于 2025-01-13 07:16:19 字数 514 浏览 0 评论 0原文

我有一些简单的代码,可以执行多分组(第一个在日期列上,第二个在 cp_flag 列上)并计算每天每个 cp_flag 的聚合总和。

df.groupby(['date', 'cp_flag']).volume.sum()

我想计算 C 和 P 之间的比率(例如,对于 2015-01-02,返回 170381/ 366072),如果可能,不使用 .apply、.transform 或 .agg。我不太清楚如何扩展当前的代码来实现这个比率计算。

输入图片此处描述

编辑:

所需的输出只是一个单独的系列,其中包含每个日期的 C/P 比率,例如

2015-01-02  0.465
...
2020-12-31  0.309

I have some simple code that does a multi-groupby (first on the date column, second on the cp_flag column) and calculates an aggregated sum for each cp_flag per day.

df.groupby(['date', 'cp_flag']).volume.sum()

I would like to calculate the ratio between C and P (e.g. for 2015-01-02, return 170381/366072) without using .apply, .transform or .agg if possible. I can't quite figure out how to extend my current code to achieve this ratio calculation.

enter image description here

Edit:

The desired output would just be an individual series with the C/P ratio for each date, e.g.

2015-01-02  0.465
...
2020-12-31  0.309

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文