简体   繁体   English

在 Python DataFrame 中查找最小值列和最小值列名称

[英]Find min value column and min value column name in Python DataFrame

I have a matrix like below and I need to create 2 more columns with minimum value from columns COL01-04 and name of that column (exluding NaN):我有一个如下所示的矩阵,我需要从 COL01-04 列和该列的名称(不包括 NaN)中创建另外 2 个具有最小值的列:

In[1]: matrix
Out[1]: 
     ID    COL01  COL02   COL03    COL04
0  0001      NaN   1662    1583   1697.4
1  0002      NaN   1006    1476  1018.44
2  0003     1452   1487  2197.5  1516.27
3  0004      NaN   1554    2298  1585.62

like this:像这样:

     ID    COL01  COL02   COL03    COL04  Min_val  Min_col
0  0001      NaN   1662    1583   1697.4     1583    COL03
1  0002      NaN   1006    1476  1018.44     1006    COL02
2  0003     1452   1487  2197.5  1516.27     1452    COL01
3  0004      NaN   1554    2298  1585.62     1554    COL02

I've already tried我已经试过了

for i in range(0, len(matrix)):
    matrix['Min_val'] = matrix[['COL01', 'COL02', 'COL03', 'COL04']].min()

but the result is NaN everywhere, type numpy.float64 .但结果到处都是NaN ,输入numpy.float64

Use DataFrame.min and DataFrame.idxmin with axis=1 for check values per rows:DataFrame.minDataFrame.idxminaxis=1用于检查每行的值:

c = ['COL01', 'COL02', 'COL03', 'COL04']
matrix[c] = matrix[c].apply(lambda x: pd.to_numeric(x, errors='coerce'))

matrix['Min_val'] = matrix[c].min(axis=1)
matrix['Min_col'] = matrix[c].idxmin(axis=1)

Or for new columns use DataFrame.assign :或者对于新列使用DataFrame.assign

matrix = matrix.assign(Min_val = matrix[c].min(axis=1), Min_col=matrix[c].idxmin(axis=1))

print (matrix)
   ID   COL01  COL02   COL03    COL04  Min_val Min_col
0   1     NaN   1662  1583.0  1697.40   1583.0   COL03
1   2     NaN   1006  1476.0  1018.44   1006.0   COL02
2   3  1452.0   1487  2197.5  1516.27   1452.0   COL01
3   4     NaN   1554  2298.0  1585.62   1554.0   COL02

you can try this :你可以试试这个:

def get_col(sr):
    name=sr.idxmin()
    value = sr[name]
    return pd.Series([value, name])
df[['Min_val','Min_col']] = df[['COL01','COL02','COL03','COL04']].apply(lambda x : get_col(x), axis=1)

df

     ID   COL01  COL02   COL03    COL04  Min_val Min_col
0  0001     NaN   1662  1583.0  1697.40   1583.0   COL03
1  0002     NaN   1006  1476.0  1018.44   1006.0   COL02
2  0003  1452.0   1487  2197.5  1516.27   1452.0   COL01
3  0004     NaN   1554  2298.0  1585.62   1554.0   COL02

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM