【问题标题】:Create a Single column using values fom multiple columns使用来自多列的值创建单列
【发布时间】:2019-06-16 17:56:26
【问题描述】:

我正在尝试根据三列的值在 Pandas 数据框中创建一个新列,如果每列 ['A','B','C'] 的值大于 5,则输出 = 1如果在任一列 ['A','B','C'] 中有任何小于 5 的值,则输出 =0 数据框如下所示:

A   B   C
5   8   6
9   2   1
6   0   0
2   2   6
0   1   2
5   8   10  
5   5   1
9   5   6

预期输出:

A   B   C    new_column
5   8   6    1
9   2   1    0
6   0   0    0   
2   2   6    0
0   1   2    0
5   8   10   1
5   5   1    0
9   5   6    1

我尝试使用此代码,但它没有给我想要的输出:

conditions = [(df['A'] >= 5) , (df['B'] >= 5) , (df['C'] >= 5)]
choices = [1,1,1]
df['new_colum'] = np.select(conditions, choices, default=0)

【问题讨论】:

  • 试试df['new_column'] = (df['A'] >= 5) & (df['B'] >= 5) & (df['C'] >= 5)

标签: python python-3.x pandas python-2.7 jupyter-notebook


【解决方案1】:

您需要&bitwise AND 提供链条件:

conditions = (df['A'] >= 5) & (df['B'] >= 5) & (df['C'] >= 5)

或者使用DataFrame.all检查行中的所有值是否都是Trues:

conditions = (df[['A','B','C']] >= 5 ).all(axis=1)
#if need all columns >=5
conditions = (df >= 5 ).all(axis=1)

然后将True, False的掩码转换为整数到1, 0

df['new_colum'] = conditions.astype(int)

或者使用numpy.where:

df['new_colum'] = np.where(conditions, 1, 0)

print (df)
   A  B   C  new_colum
0  5  8   6          1
1  9  2   1          0
2  6  0   0          0
3  2  2   6          0
4  0  1   2          0
5  5  8  10          1
6  5  5   1          0
7  9  5   6          1

【讨论】:

    猜你喜欢
    • 2015-01-17
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2023-03-08
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多