【问题标题】:how to create a column with the index of the biggest among other columns AND some condition如何在其他列中创建一个索引最大的列和一些条件
【发布时间】:2022-11-18 02:56:47
【问题描述】:

我有一个包含一些列的数据集,我想创建另一列,其中值是具有最高值的变量的列名但不同于 1

例如:

df = pd.DataFrame({'A': [1, 0.2, 0.1, 0],
                    'B': [0.2,1, 0, 0.5],
                    'C': [1, 0.4, 0.3, 1]},
                   index=['1', '2', '3', '4'])
df
index A B C
1 1.0 0.2 1.0
2 0.2 1.0 0.4
3 0.1 0.0 0.3
4 0.0 0.5 1.0

应该给出类似的输出

index A B C NEWCOL
1 1.0 0.2 1.0 B
2 0.2 0.3 0.1 C
3 0.1 0.4 0.2 B
4 0.0 0.5 1.0 B
df2['newcol'] = df2.idxmax(axis=1) if df2.max(index=1) != 1 

但没用

【问题讨论】:

    标签: pandas dataframe numpy dataset


    【解决方案1】:

    这是一种方法

    # filter out the data that is 1 and find the id of the max value using idxmax
    df['newcol']=df[~df.isin([1])].idxmax(axis=1)
    df
    
          A       B     C   newcol
    1   1.0     0.2     1.0     B
    2   0.2     1.0     0.4     C
    3   0.1     0.0     0.3     C
    4   0.0     0.5     1.0     B
    

    附言:您的输入、起始和预期数据不匹配。以上是基于输入的DF

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2017-08-26
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2021-01-16
      • 2020-06-02
      • 1970-01-01
      • 2017-08-12
      相关资源
      最近更新 更多