问题描述
我正在按 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.
推荐答案
我觉得你想多了.只需使用 groupby
和 idxmin
:
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:关键词]
发布评论