python - 查找每行具有前 3 个最大值的列名称

标签 python

例如数据如下:

df={'a1':[5,6,3,2,5],'a2':[23,43,56,2,6], 'a3':[4,2,3,6,7], 'a4':[1,2,1,3,2],'a5':[4,98,23,5,7],'a6':[5,43,3,2,5]}
x=pd.DataFrame(df)
Out[260]: 
    a1  a2  a3  a4  a5  a6
0   5  23   4   1   4   5
1   6  43   2   2   98   43
2   3  56   3   1  23   3
3   2   2   6   3   5   2
4   5   6   7   2   7   5

我需要这样的结果:

top1 top2 top3
a2   a1   a6
a5   a2   a6
....

我看到了推荐 idxmax 的先前问题的答案(见下文)。但是如何处理前 n 个值 (n>1)?

Find the column name which has the maximum value for each row

更新:

我发现答案非常有用,但唯一的问题是我的数据很长,所以必须想办法绕过它。我最终将数据保存到一个 csv 文件,然后分块读回。这是我使用的代码:

data = pd.read_csv('xxx.csv', chunksize=1000)
rslt = pd.DataFrame(np.zeros((0,3)), columns=['top1','top2','top3'])
for chunk in data:
    x=pd.DataFrame(chunk).T
    for i in x.columns:
        df1row = pd.DataFrame(x.nlargest(3, i).index.tolist(), index=['top1','top2','top3']).T
        rslt = pd.concat([rslt, df1row], axis=0)
rslt=rslt.reset_index(drop=True)

最佳答案

import pandas as pd
import numpy as np

df={'a1':[5,6,3,2,5],'a2':[23,43,56,2,6], 'a3':[4,2,3,6,7], 'a4':[1,2,1,3,2],'a5':[4,98,23,5,7],'a6':[5,43,3,2,5]}
df=pd.DataFrame(df)

df


   a1  a2  a3  a4  a5  a6
0   5  23   4   1   4   5
1   6  43   2   2  98  43
2   3  56   3   1  23   3
3   2   2   6   3   5   2
4   5   6   7   2   7   5

我们可以使用 numpyargsortpandas< 的 applylambda 来解决它。 解决方案:

Tops =pd.DataFrame(df.apply(lambda x:list(df.columns[np.array(x).argsort()[::-1][:3]]), axis=1).to_list(),  columns=['Top1', 'Top2', 'Top3'])


Tops

我们得到:

  Top1 Top2 Top3
0   a2   a6   a1
1   a5   a6   a2
2   a2   a5   a6
3   a3   a5   a4
4   a5   a3   a2

关于python - 查找每行具有前 3 个最大值的列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494844/

相关文章:

python - 为什么可以将bcrypt.hashpw同时用于哈希和验证密码?

python - PIP 安装失败,库语法错误

python - SQLite 和 Sqlalchemy Singleton 线程池 - 我可以共享连接对象吗?

python - selenium execute_script 给出错误

python - 在 CrawlSpider 中以什么顺序评估规则?

python 正则表达式匹配一个组或不匹配它

python - 按星期几排序列?

python - 补丁中的 matplotlib 颜色渐变?

python - 值错误 : I/O operation on closed file even after giving second arg for open()

python - 在 scipy 上寻求与 optimize.fmin 的收敛