如何 select 行中的第二个最小值和 return 它们各自的列名?

How to select 2nd smallest values in rows and return their respective column names?

我有一个包含很多列的数据框,其中包含很多整数值。我想 return 列的名称,作为行中第二小的值。

我能够 return 行中最低值的列名,这非常简单:

import pandas as pd

matrix = [(22, 2, 13),
          (9, 1, 5),
          (5, 4, 3),
          (6, 3, 1),
          (1, 2, 20)]

dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))

minValueIndexObj = dfObj.idxmin(axis=1)
print("min values of row are at following columns :")
print(minValueIndexObj)

Out[]:
min values of row are at following columns :
a    y
b    y
c    z
d    z
e    x
dtype: object

第 'a' 行的第 'y' 列的值最小。

接下来我需要的是:

2nd min values of row are at following columns :
a    z
b    z
c    y
d    y
e    y
dtype: object

感谢您的支持。

使用 argsort 按排序值排列所有列名称的数组:

a = dfObj.columns.values[np.argsort(dfObj.values)]
print (a)
[['y' 'z' 'x']
 ['y' 'z' 'x']
 ['z' 'y' 'x']
 ['z' 'y' 'x']
 ['x' 'y' 'z']]

然后select'columns'通过索引传递给Series构造函数:

print (pd.Series(a[:, 0], index=dfObj.index))
a    y
b    y
c    z
d    z
e    x
dtype: object

print (pd.Series(a[:, 1], index=dfObj.index))
a    z
b    z
c    y
d    y
e    y
dtype: object