gpt4 book ai didi

python - 如何获取单行数据框中与 n 个最大值对应的列?

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:14 26 4
gpt4 key购买 nike

我有一个这样的数据框

    c0   c1   c2   c3   c4   c5
0 2 4 3 1 6 5

并希望获取与单行中的 n 最大值对应的列,例如n=3

    c4   c5   c1
0 6 5 4

我怎样才能最有效地实现这一点(w.r.t. 内存使用、执行时间和与 dask 并行化的能力)?

作为引用 w.r.t.性能 @stark 的答案(500 列的数据框,n=10):使用 df.sort_values(0, axis='columns', ascending=False).iloc[:, :n] I使用 %%timeit 获得 649 µs

最佳答案

使用 numpy - np.argsort对于排序值的位置,获取前 3 个值 使用和 iloc 选择:

df = df.iloc[:, np.argsort(-df.values[0])[:3]]
print (df)
c4 c5 c1
0 6 5 4

关于python - 如何获取单行数据框中与 n 个最大值对应的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59031823/

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