分组时保留其他列 [英] Keep other columns when doing groupby

查看:210
本文介绍了分组时保留其他列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫数据帧上使用groupby来删除所有没有特定列的最小值的行.像这样:

I'm using groupby on a pandas dataframe to drop all rows that don't have the minimum of a specific column. Something like this:

df1 = df.groupby("item", as_index=False)["diff"].min()

但是,如果我不止这两列,其他列(例如我的示例中的otherstuff)将被删除.我可以使用groupby保留这些列,还是必须找到一种不同的方式删除行?

However, if I have more than those two columns, the other columns (e.g. otherstuff in my example) get dropped. Can I keep those columns using groupby, or am I going to have to find a different way to drop the rows?

我的数据如下:

    item    diff   otherstuff
   0   1       2            1
   1   1       1            2
   2   1       3            7
   3   2      -1            0
   4   2       1            3
   5   2       4            9
   6   2      -6            2
   7   3       0            0
   8   3       2            9

,最终应该像:

    item   diff  otherstuff
   0   1      1           2
   1   2     -6           2
   2   3      0           0

但是我得到的是:

    item   diff
   0   1      1           
   1   2     -6           
   2   3      0                 

我一直在浏览文档,找不到任何东西.我试过了:

I've been looking through the documentation and can't find anything. I tried:

df1 = df.groupby(["item", "otherstuff"], as_index=false)["diff"].min()

df1 = df.groupby("item", as_index=false)["diff"].min()["otherstuff"]

df1 = df.groupby("item", as_index=false)["otherstuff", "diff"].min()

但是这些都不起作用(我最后一个意识到,语法是在创建组之后进行聚合的.)

But none of those work (I realized with the last one that the syntax is meant for aggregating after a group is created).

推荐答案

方法#1:使用idxmin()获取最小diff元素的 indices ,然后选择以下元素:

Method #1: use idxmin() to get the indices of the elements of minimum diff, and then select those:

>>> df.loc[df.groupby("item")["diff"].idxmin()]
   item  diff  otherstuff
1     1     1           2
6     2    -6           2
7     3     0           0

[3 rows x 3 columns]

方法2:按diff排序,然后获取每个item组中的第一个元素:

Method #2: sort by diff, and then take the first element in each item group:

>>> df.sort_values("diff").groupby("item", as_index=False).first()
   item  diff  otherstuff
0     1     1           2
1     2    -6           2
2     3     0           0

[3 rows x 3 columns]

请注意,即使行内容相同,结果索引也不同.

Note that the resulting indices are different even though the row content is the same.

这篇关于分组时保留其他列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆