【问题标题】:How to add a column that contains the corresponding column name with the largest number in Python?如何在Python中添加包含对应列名最大的列?
【发布时间】:2019-11-17 21:49:39
【问题描述】:

我有一个这样的数据框:

A1 A2 A3 ...A99 largest
0   3  4  6      11   11
1   1  8  2  ...  1    8
.
.
.

我使用以下方法创建了每行中包含最大值的列:

data['largest']=data.max(axis=1)

但我也想得到一列,其中包含具有最大数字的相应列名,如下所示:

    A1 A2 A3 ...A99 largest name
0   3  4  6      11   11    A99
1   1  8  2  ...  1    8    A2
.                            .
.                            .
.                            .

我尝试了'.idxmax',但给了我一个错误'reduction operation 'argmax' not allowed for this dtype',有人可以帮我吗?非常感谢。

【问题讨论】:

    标签: python pandas dataframe max data-science


    【解决方案1】:

    这是使用dot 将列名保留在值等于largest 的一种方法:

    df['name'] = df.iloc[:,:-1].eq(df.largest.values[:,None]).dot(df.columns[:-1])
    
       A1  A2  A3  A99  largest name
    0   3   4   6   11       11  A99
    1   1   8   2    1        8   A2
    

    【讨论】:

    • 我收到错误“形状 (100,)”和 (50,),未对齐:100(dim 0)!=50(dim 0)
    【解决方案2】:

    使用np.argmax():

    df=df.assign(name=df.columns[np.argmax(df.values,axis=1)])
    

       A1  A2  A3  A99  largest name
    0   3   4   6   11       11  A99
    1   1   8   2    1        8   A2
    

    【讨论】:

      【解决方案3】:

      使用DataFrame.idxmaxDataFrame.assign 来添加2 列而不相互推断:

      df = data.assign(largest=data.max(axis=1), name=data.idxmax(axis=1))
      print (df)
         A1  A2  A3  A99  largest name
      0   3   4   6   11       11  A99
      1   1   8   2    1        8   A2
      

      DataFrame.agg:

      data[['largest','name']] = data.agg(['max','idxmax'], 1)
      print (data)
         A1  A2  A3  A99 largest name
      0   3   4   6   11      11  A99
      1   1   8   2    1       8   A2
      

      编辑:

      您只能选择数字列:

      df1 = data.select_dtypes(np.number)
      

      或将列转换为数字:

      df1 = data.astype(int)
      

      如果不工作 .astype 因为可能有一些非数值使用 to_numericerrors='coerce' 来转换有问题的值 no NaN

      df1 = data.apply(lambda x: pd.to_numeric(x, errors='coerce'))
      

      df = data.assign(largest=df1.max(axis=1), name=df1.idxmax(axis=1))
      

      【讨论】:

      • 感谢您的回答,我实际上尝试了 '.idxmax' 但给了我一个错误'reduction operation 'argmax' not allowed for this dtype',我不知道为什么会出现这种情况,因为我检查了数据类型,它是数据帧类型
      • @Cecilia - 似乎有些列不是数字的,请稍等。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多