I am trying to color points of a pandas dataframe depending on TWO conditions. Example:
JavaScript
x
3
1
IF value of col1 > a AND value of col2 - value of col3 < b THEN value of col4 = string
2
ELSE value of col4 = other string.
3
I have tried so many different ways now and everything I found online was only depending on one condition.
My example code always raises the Error:
JavaScript
1
2
1
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
2
Here’s the code. Tried several variations without success.
JavaScript
1
13
13
1
df = pd.DataFrame()
2
3
df['A'] = range(10)
4
df['B'] = range(11,21,1)
5
df['C'] = range(20,10,-1)
6
7
borderE = 3.
8
ex = 0.
9
10
#print df
11
12
df['color'] = np.where(all([df.A < borderE, df.B - df.C < ex]), 'r', 'b')
13
Btw: I understand, what it says but not how to handle it.
Advertisement
Answer
Selection criteria uses Boolean indexing:
JavaScript
1
15
15
1
df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b')
2
3
>>> df
4
A B C color
5
0 0 11 20 r
6
1 1 12 19 r
7
2 2 13 18 r
8
3 3 14 17 b
9
4 4 15 16 b
10
5 5 16 15 b
11
6 6 17 14 b
12
7 7 18 13 b
13
8 8 19 12 b
14
9 9 20 11 b
15