如何在pandas中的Excel枢轴表函数中使用分组功能?

发布于 2025-01-23 07:36:07 字数 2224 浏览 0 评论 0原文

我有熊猫数据框架。

idScoreAction_flag
S110.585366Not Traded
P5550.457778Not Traded
B280.636154Not Traded
A8590.000000Traded
P5560.761905Not Traded
Y4610.333333Not Traded
S1210.444444Not Traded
K4810.000000Traded
S1221.000000Not Traded
R5560.000000Traded
R6270.602778Traded

In excel using pivot table and grouping我能够做到这一点。

如何使用pandas

”“在此处输入图像描述”

和pivot Table ”在此处输入图像描述”

I have a pandas dataframe.

idScoreAction_flag
S110.585366Not Traded
P5550.457778Not Traded
B280.636154Not Traded
A8590.000000Traded
P5560.761905Not Traded
Y4610.333333Not Traded
S1210.444444Not Traded
K4810.000000Traded
S1221.000000Not Traded
R5560.000000Traded
R6270.602778Traded

In excel using pivot table and grouping I was able to do this.

How to achieve this using pandas

enter image description here

And pivot table enter image description here

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

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

发布评论

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

评论(1

給妳壹絲溫柔 2025-01-30 07:36:07

iiuc,您可以使用pd.cut创建垃圾箱,然后使用crosstab获取每个操作标志的计数。最后,分配对新列“ Grand_total”的行总计:

out = pd.crosstab(pd.cut(df['Score'], np.linspace(0,1,21), include_lowest=True), df['Action_flag']).assign(Grand_total=lambda x: x.sum(axis=1))

输出:

Action_flag     Not Traded  Traded  Grand_total
Score                                          
(-0.001, 0.05]           0       3            3
(0.3, 0.35]              1       0            1
(0.4, 0.45]              1       0            1
(0.45, 0.5]              1       0            1
(0.55, 0.6]              1       0            1
(0.6, 0.65]              1       1            2
(0.75, 0.8]              1       0            1
(0.95, 1.0]              1       0            1

IIUC, you could create bins using pd.cut, then use crosstab to get the counts each each action flag. Finally, assign the row-wise totals to a new column "Grand_total":

out = pd.crosstab(pd.cut(df['Score'], np.linspace(0,1,21), include_lowest=True), df['Action_flag']).assign(Grand_total=lambda x: x.sum(axis=1))

Output:

Action_flag     Not Traded  Traded  Grand_total
Score                                          
(-0.001, 0.05]           0       3            3
(0.3, 0.35]              1       0            1
(0.4, 0.45]              1       0            1
(0.45, 0.5]              1       0            1
(0.55, 0.6]              1       0            1
(0.6, 0.65]              1       1            2
(0.75, 0.8]              1       0            1
(0.95, 1.0]              1       0            1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文