如何在 pandas 中的 DataFrame 的列中提取第 n 个 maximum/minimum 值?

How to extract the n-th maximum/minimum value in a column of a DataFrame in pandas?

我想从 pandas 的 DataFrame 的数字列中获取第 n 个最小值或第 n 个最大值。

示例:

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。

您可以使用 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

此处快速观察 - 这种操作无法向量化。您实际上是在执行两个完全不同的操作。

df =  
     a    b
0  3.0  1.0
1  2.0  4.0
2  4.0  2.0
3  1.0  3.0

df.nlargest(3,'a')
   =2.0

df.nsmallest(2,'b')=2.0