使用np.where基于多个列的pandas多个条件

时间:2016-04-13 15:25:44

标签: python numpy pandas conditional-statements

我试图在两个条件下对大熊猫数据帧的颜色进行着色。例如:

如果col1的值> a(float)AND col2的值 - col3的值< b(float),然后col 4 = string的值,否则:其他字符串。

我现在尝试了很多不同的方法,我在网上发现的一切只取决于一个条件。

我的示例代码总是引发错误: 系列的真值是模棱两可的。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

这是代码。尝试了几种不同的变化。

df = pd.DataFrame()

df['A'] = range(10)
df['B'] = range(11,21,1)
df['C'] = range(20,10,-1)

borderE = 3.
ex = 0.

#print df

df['color'] = np.where(all([df.A < borderE, df.B - df.C < ex]), 'r', 'b')
顺便说一句:我明白,它说的是什么,但不知道如何处理...... 提前谢谢!

2 个答案:

答案 0 :(得分:14)

选择标准使用Boolean indexing

df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b')

>>> df
   A   B   C color
0  0  11  20     r
1  1  12  19     r
2  2  13  18     r
3  3  14  17     b
4  4  15  16     b
5  5  16  15     b
6  6  17  14     b
7  7  18  13     b
8  8  19  12     b
9  9  20  11     b

答案 1 :(得分:5)

将IF包装在函数中并应用它:

def color(row):
    borderE = 3.
    ex = 0.
    if (row.A > borderE) and( row.B - row.C < ex) :
        return "somestring"
    else:
        return "otherstring"

df.loc[:, 'color'] = df.apply(color, axis = 1)

收率:

  A   B   C        color
0  0  11  20  otherstring
1  1  12  19  otherstring
2  2  13  18  otherstring
3  3  14  17  otherstring
4  4  15  16   somestring
5  5  16  15  otherstring
6  6  17  14  otherstring
7  7  18  13  otherstring
8  8  19  12  otherstring
9  9  20  11  otherstring
相关问题