【问题标题】:New column based on another multiple dataframe columns基于另一个多个数据框列的新列
【发布时间】:2022-07-18 18:21:35
【问题描述】:

下面是我的数据框。 |一个 |乙 | |---|---| | 12| 0 | | 1 | 21| | 0 | 0 |

现在想添加一个列名“c”,当 a 或 b 为非零时返回 yes,当 a 和 b 为零时返回 no

a b c
12 0 yes
1 21 yes
0 0 no

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    如果需要通过0 测试所有列比较,并通过DataFrame.all 测试每行的所有值是否设置yesnumpy.where '否':

    df['c'] = np.where(df.eq(0).all(axis=1), 'no','yes')
    
    print (df)
        a   b    c
    0  12   0  yes
    1   1  21  yes
    2   0   0   no
    

    另一个想法:

    df['c'] = df.ne(0).any(axis=1).map({False: 'no',True:'yes'})
    

    如果可能有多个列并且只需要测试a,b 列:

    cols = ['a','b']
    df['c'] = np.where(df[cols].eq(0).all(axis=1), 'no','yes')
    

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多