python - 如何选择行中的第二个最小值并返回它们各自的列名?

标签 python pandas dataframe matrix min

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

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

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']]

然后通过索引选择'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

关于python - 如何选择行中的第二个最小值并返回它们各自的列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607944/

相关文章:

python - pandas DataFrame 中 x 天内每个元素的累积乘积

python - 类型错误 : Object of type 'Tag' is not JSON serializable

python - 如何删除 Pandas 中仅包含零的列?

python - 使用至少一个匹配条件过滤组上的 DataFrame

python - 获取正值之和与负值之和

python - Pandas 数据帧 : using the output of a function in row x as input for the same function in row x+1

python - 必填字段 'sessionHandle' 未设置!在将配置单元与 python 一起使用时

python - 每第 n 行 Pandas iloc 复杂切片

python - Pandas:将 CSV 中的 x 轴日期映射到 y 轴

python - Pandas 自合并阻塞了缺失的结构