pandas Groupby和总和只有一栏

编程入门 行业动态 更新时间:2024-10-28 07:21:24
本文介绍了 pandas Groupby和总和只有一栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有一个数据帧df1,看起来像下面的样子:

So I have a dataframe, df1, that looks like the following:

A B C 1 foo 12 California 2 foo 22 California 3 bar 8 Rhode Island 4 bar 32 Rhode Island 5 baz 15 Ohio 6 baz 26 Ohio

我想按A列分组,然后对B列求和,同时将值保留在C列中.

I want to group by column A and then sum column B while keeping the value in column C. Something like this:

A B C 1 foo 34 California 2 bar 40 Rhode Island 3 baz 41 Ohio

问题是,当我说df.groupby('A').sum()列C被删除时返回

The issue is, when I say df.groupby('A').sum() column C gets removed returning

B A bar 40 baz 41 foo 34

当我进行分组和求和时,如何解决此问题并保留C列?

How can I get around this and keep column C when I group and sum?

推荐答案

执行此操作的唯一方法是将C包含在groupby中(groupby函数可以接受列表).

The only way to do this would be to include C in your groupby (the groupby function can accept a list).

尝试一下:

df.groupby(['A','C'])['B'].sum()

要注意的另一件事是,如果需要在聚合后使用df,则还可以使用as_index = False选项返回数据框对象.当我第一次和熊猫一起工作时,这给我带来了麻烦.示例:

One other thing to note, if you need to work with df after the aggregation you can also use the as_index=False option to return a dataframe object. This one gave me problems when I was first working with Pandas. Example:

df.groupby(['A','C'], as_index=False)['B'].sum()

更多推荐

pandas Groupby和总和只有一栏

本文发布于:2023-10-14 19:02:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1491928.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   pandas   Groupby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!