gpt4 book ai didi

python - 如何提取 Pandas DataFrame列中的第n个最大值/最小值?

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:11 27 4
gpt4 key购买 nike

我想从 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

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

关于python - 如何提取 Pandas DataFrame列中的第n个最大值/最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48026397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com