gpt4 book ai didi

Python数据框找到top-5的索引,然后索引到另一列

转载 作者:行者123 更新时间:2023-11-30 22:15:26 27 4
gpt4 key购买 nike

我有一个包含两个数字列 A 和 B 的数据框。我想从 A 列中查找前 5 个值,并返回前 5 个位置中的 B 列中的值。

非常感谢。

最佳答案

我认为需要DataFrame.nlargestA 列指定为前 5 行,然后选择 B 列:

df = pd.DataFrame({'A':[4,5,26,43,54,36,18,7,8,9],
'B':range(10)})

print (df)
A B
0 4 0
1 5 1
2 26 2
3 43 3
4 54 4
5 36 5
6 18 6
7 7 7
8 8 8
9 9 9
<小时/>
print (df.nlargest(5, 'A'))
A B
4 54 4
3 43 3
5 36 5
2 26 2
6 18 6

a = df.nlargest(5, 'A')['B']
print (a)
4 4
3 3
5 5
2 2
6 6
Name: B, dtype: int64

排序的替代解决方案:

a = df.sort_values('A', ascending=False)['B'].head(5)
print (a)
4 4
3 3
5 5
2 2
6 6
Name: B, dtype: int64

关于Python数据框找到top-5的索引,然后索引到另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304103/

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