python - 获取数据帧中每行中的前 n 个值及其出现的列名称

标签 python pandas dataframe top-n

我有一个像这样的数据框:

df = pd.DataFrame({'a':[1,2,1],'b':[4,6,0],'c':[0,4,8]})
+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 4 | 0 |
+---+---+---+
| 2 | 6 | 4 |
+---+---+---+
| 1 | 0 | 8 |
+---+---+---+

对于每一行,我需要(两者)“n”(在本例中为两个)最高值以及按降序排列的相应列:

row 1: 'b':4,'a':1
row 2: 'b':6,'c':4
row 3: 'c':8,'a':1

最佳答案

这里有两种方式,均改编自@unutbu's answer to "Find names of top-n highest-value columns in each pandas dataframe row"

1) 使用 Python Decorate-Sort-Undecorate 并在每行上使用 .apply(lambda ...) 插入列名称,执行 np.argsort,保留顶部-n,重新格式化答案。 (我认为这更干净)。

import numpy as np

# Apply Decorate-Sort row-wise to our df, and slice the top-n columns within each row...

sort_decr2_topn = lambda row, nlargest=2:
    sorted(pd.Series(zip(df.columns, row)), key=lambda cv: -cv[1]) [:nlargest]

tmp = df.apply(sort_decr2_topn, axis=1)

0    [(b, 4), (a, 1)]
1    [(b, 6), (c, 4)]
2    [(c, 8), (a, 1)]

# then your result (as a pandas DataFrame) is...
np.array(tmp)
array([[('b', 4), ('a', 1)],
       [('b', 6), ('c', 4)],
       [('c', 8), ('a', 1)]], dtype=object)
# ... or as a list of rows is
tmp.values.tolist()
#... and you can insert the row-indices 0,1,2 with 
zip(tmp.index, tmp.values.tolist())
[(0, [('b', 4), ('a', 1), ('c', 0)]), (1, [('b', 6), ('c', 4), ('a', 2)]), (2, [('c', 8), ('a', 1), ('b', 0)])]

2) 获取 topnlocs 矩阵,如下所示,然后使用它重新索引到 df.columns 和 df.values,并合并该输出:

import numpy as np

nlargest = 2
topnlocs = np.argsort(-df.values, axis=1)[:, 0:nlargest]
# ... now you can use topnlocs to reindex both into df.columns, and df.values, then reformat/combine them somehow
# however it's painful trying to apply that NumPy array of indices back to df or df.values,

参见How to get away with a multidimensional index in pandas

关于python - 获取数据帧中每行中的前 n 个值及其出现的列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433682/

相关文章:

python - Django REST Framework 出现意外的关键字参数 TypeError

python - 如何使 Pandas 中的行操作更快?目前发布代码需要 13 小时

python - 具有不同 X 轴顺序的 Pandas groupby 图

python - 比较 Dataframe 中的每个值以创建新的 Dataframe

python - 如何将 .ipynb 文件上传到笔记本云实例?

python - 为什么 sympy.arg() 函数没有返回预期的输出?

excel - 将一个数据框与另一个数据框重叠并仅保留新的或更改的行

python - 将属性(不是函数)传递给 python `pandas.DataFrame.style`

python - Pandas DataFrame 多索引重新索引列不起作用

python - PyQT - 定位和显示自定义小部件