[英]Pandas GroupBy and select rows with the minimum value in a specific column
我按 A 列对我的数据集进行分组,然后想取 B 列中的最小值和 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 分组,并创建一个值来指示我将在数据集中保留的行:
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)]
我确信有一种更直接的方法可以做到这一点。 我在这里看到了许多使用多索引的答案,但我想这样做而不向我的 dataframe 添加多索引。 谢谢您的帮助。
我觉得你想多了。 只需使用groupby
和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
有类似的情况,但列标题更复杂(例如“B val”) ,在这种情况下需要这样做:
df.loc[df.groupby('A')['B val'].idxmin()]
接受的答案(建议idxmin
)不能与管道模式一起使用。 管道友好的替代方法是首先对值进行排序,然后将groupby
与DataFrame.head
一起使用:
data.sort_values('B').groupby('A').apply(DataFrame.head, n=1)
这是可能的,因为默认情况下groupby
保留每个 group 中的行顺序,这是稳定且记录在案的行为(请参阅pandas.DataFrame.groupby
)。
这种方法有额外的好处:
.sort_values()
提供另一列(作为列表)来打破关系,例如: data.sort_values(['final_score', 'midterm_score']).groupby('year').apply(DataFrame.head, n=1)
与其他答案一样,要完全匹配问题.reset_index(drop=True)
中所需的结果,需要制作最终片段:
df.sort_values('B').groupby('A').apply(DataFrame.head, n=1).reset_index(drop=True)
我找到了一个更冗长但效率更高的答案:
这是示例数据集:
data = pd.DataFrame({'A': [1,1,1,2,2,2], 'B':[4,5,2,7,4,6], 'C':[3,4,10,2,4,6]})
data
Out:
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
首先,我们将从 groupby 操作中获取 Series 的最小值:
min_value = data.groupby('A').B.min()
min_value
Out:
A
1 2
2 4
Name: B, dtype: int64
然后,我们将这个系列结果合并到原始数据框上
data = data.merge(min_value, on='A',suffixes=('', '_min'))
data
Out:
A B C B_min
0 1 4 3 2
1 1 5 4 2
2 1 2 10 2
3 2 7 2 4
4 2 4 4 4
5 2 6 6 4
最后,我们只得到 B 等于 B_min 的行并删除 B_min,因为我们不再需要它了。
data = data[data.B==data.B_min].drop('B_min', axis=1)
data
Out:
A B C
2 1 2 10
4 2 4 4
我已经在非常大的数据集上对其进行了测试,这是我可以让它在合理的时间内工作的唯一方法。
解决方案是,如前所述;
df.loc[df.groupby('A')['B'].idxmin()]
如果解决方案,但如果出现错误;
"Passing list-likes to .loc or [] with any missing labels is no longer supported.
The following labels were missing: Float64Index([nan], dtype='float64').
See https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike"
就我而言,B 列有“NaN”值。所以,我使用了“dropna()”,然后它就起作用了。
df.loc[df.groupby('A')['B'].idxmin().dropna()]
您还可以 boolean 索引B
列最小值的行
out = df[df['B'] == df.groupby('A')['B'].transform('min')]
print(out)
A B C
2 1 2 10
4 2 4 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.