如何在 pandas 的DataFrame的列中提取第n个最大值/最小值? [英] How to extract the n-th maximum/minimum value in a column of a DataFrame in pandas?
本文介绍了如何在 pandas 的DataFrame的列中提取第n个最大值/最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从熊猫DataFrame
中的数字列中获取第n个最小值或第n个最大值.
I would like to obtain the n-th minimum or the n-th maximum value from numerical columns in the DataFrame
in pandas.
示例:
df = pd.DataFrame({'a': [3.0, 2.0, 4.0, 1.0],'b': [1.0, 4.0 , 2.0, 3.0]})
a b
0 3.0 1.0
1 2.0 4.0
2 4.0 2.0
3 1.0 3.0
列a
中的第三最大值是2,列b
中的第二最小值也是2.
The third largest value in column a
is 2 and the second smallest value in column b
is also 2.
推荐答案
您可以使用nlargest
/nsmallest
-
df
a b
0 3.0 1.0
1 2.0 4.0
2 4.0 2.0
3 1.0 3.0
df.a.nlargest(3).iloc[-1]
2.0
或者
df.a.nlargest(3).iloc[[-1]]
1 2.0
Name: a, dtype: float64
而且,对于b
-
df.b.nsmallest(2).iloc[-1]
2.0
或者,
df.b.nsmallest(2).iloc[[-1]]
2 2.0
Name: b, dtype: float64
此处快速观察-此类操作无法矢量化.您实际上是在这里执行两个完全不同的操作.
Quick observation here - this sort of operation cannot be vectorised. You are essentially performing two completely different operations here.
这篇关于如何在 pandas 的DataFrame的列中提取第n个最大值/最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文