Pandas GroupBy 并选择特定列中具有最小值的行

编程入门 行业动态 更新时间:2024-10-18 01:32:13
本文介绍了Pandas GroupBy 并选择特定列中具有最小值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按 A 列对我的数据集进行分组,然后想取 B 列中的最小值和 C 列中的相应值.

I am grouping my dataset by column A and then would like to take the minimum value in column B and the corresponding value in column C.

data = pd.DataFrame({'A': [1, 2], 'B':[ 2, 4], 'C':[10, 4]})
data  
    A   B   C
0   1   4   3
1   1   5   4
2   1   2   10
3   2   7   2
4   2   4   4
5   2   6   6  

我想得到:

    A   B   C
0   1   2   10
1   2   4   4

目前我按 A 分组,并创建一个值来指示我将保留在数据集中的行:

For the moment I am grouping by A, and creating a value that indicates me the rows I will keep in my dataset:

a = data.groupby('A').min()
a['A'] = a.index
to_keep = [str(x[0]) + str(x[1]) for x in a[['A', 'B']].values]
data['id'] = data['A'].astype(str) + data['B'].astype('str')
data[data['id'].isin(to_keep)]

我相信有一种更直接的方法可以做到这一点.我在这里看到了许多使用多索引的答案,但我想这样做而不向我的数据帧添加多索引.感谢您的帮助.

I am sure that there is a much more straight forward way to do this. I have seen many answers here that use multi-indexing but I would like to do this without adding multi-index to my dataframe. Thank you for your help.

推荐答案

我觉得你想多了.只需使用 groupbyidxmin:

I feel like you're overthinking this. Just use groupby and idxmin:

df.loc[df.groupby('A').B.idxmin()]

   A  B   C
2  1  2  10
4  2  4   4

<小时>

df.loc[df.groupby('A').B.idxmin()].reset_index(drop=True)

   A  B   C
0  1  2  10
1  2  4   4

这篇关于Pandas GroupBy 并选择特定列中具有最小值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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