在每个 pandas 数据框行中查找前n个最高值(非零)的列的名称 [英] Find names of top-n highest-value (non-zero) columns in each pandas dataframe row

查看:70
本文介绍了在每个 pandas 数据框行中查找前n个最高值(非零)的列的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有类似

id     p1 p2 p3 p4  
1      0  9  0  4
2      0  0  0  4
3      1  3 10  7
4      1  5  3  1
5      2  3  7 10

想在每个熊猫数据框行中找到前n个最高值列的列名,并希望从前3个值中排除零值.

Want to find column names of top-n highest-value columns in each pandas data frame row and want to exclude zero value from top 3.

id top1 top2 top3
1  p2   p4   
2  p4      
3  p3   p4   p2
4  p2   p3   p4/p1
5  p4   p3   p2

当前解决方案返回的列名称也具有零.有没有办法排除零值.有这个解决方案

The present solutions return column names which are having zero too. Is there way to exclude zero values. have this solution

arank = df.apply(np.argsort, axis = 1)
ranked_cols = df.columns.to_series()[arank.values[:,::-1][:,:3]]
new_df = pd.DataFrame(ranked_cols, index=df.index)

还有其他解决方案,例如

there also other solutions such as Find names of top-n highest-value columns in each pandas dataframe row. Can these be modified to exclude columns with zero value?

推荐答案

您需要重新排序 values by column names ,以及在哪里0替换为 mask 清空字符串:

You need reorder values by column names, and where 0 replace by mask to empty strings:

df = df.set_index('id')

k = 3
vals = df.values
arr1 = np.argsort(-vals, axis=1)

print (vals[np.arange(len(df.index))[:,None], arr1][:,:k])
[[ 9  4  0]
 [ 4  0  0]
 [10  7  3]
 [ 5  3  1]
 [10  7  3]]

a = df.columns[arr1[:,:k]]
mask = vals[np.arange(len(df.index))[:,None], arr1][:,:k] == 0
print (mask)
[[False False  True]
 [False  True  True]
 [False False False]
 [False False False]
 [False False False]]

result = pd.DataFrame(a, columns=['top{}'.format(i) for i in range(1, k+1)],
                         index=df.index)

result = result.mask(mask, '')
print(result)
   top1 top2 top3
id               
1    p2   p4     
2    p4          
3    p3   p4   p2
4    p2   p3   p1
5    p4   p3   p2

这篇关于在每个 pandas 数据框行中查找前n个最高值(非零)的列的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆