Below is the code and output, what I’m trying to get is shown in the “exp” column, as you can see the “countif” column just counts 5 columns, but I want it to only count negative values.
So for example: index 0, df1[0]
should equal 2
What am I doing wrong?
Python
JavaScript
x
15
15
1
import pandas as pd
2
import numpy as np
3
4
a = ['A','B','C','B','C','A','A','B','C','C','A','C','B','A']
5
b = [2,4,1,1,2,5,-1,2,2,3,4,3,3,3]
6
c = [-2,4,1,-1,2,5,1,2,2,3,4,3,3,3]
7
d = [-2,-4,1,-1,2,5,1,2,2,3,4,3,3,3]
8
exp = [2,1,0,2,0,0,1,0,0,0,0,0,0,0]
9
10
df1 = pd.DataFrame({'b':b,'c':c,'d':d,'exp':exp}, columns=['b','c','d','exp'])
11
df1['sumif'] = df1.where(df1<0,0).sum(1)
12
df1['countif'] = df1.where(df1<0,0).count(1)
13
df1
14
# df1.sort_values(['a','countif'], ascending=[True, True])
15
Output
Advertisement
Answer
First DataFrame.where
working different, it replace False
values to 0
here by condition (here False are greater of equal 0
), so cannot be used for count:
JavaScript
1
17
17
1
print (df1.iloc[:, :3].where(df1<0,0))
2
b c d
3
0 0 -2 -2
4
1 0 0 -4
5
2 0 0 0
6
3 0 -1 -1
7
4 0 0 0
8
5 0 0 0
9
6 -1 0 0
10
7 0 0 0
11
8 0 0 0
12
9 0 0 0
13
10 0 0 0
14
11 0 0 0
15
12 0 0 0
16
13 0 0 0
17
You need compare first 3 columns for less like 0
and sum
:
JavaScript
1
21
21
1
df1['exp1'] = (df1.iloc[:, :3] < 0).sum(1)
2
3
#If need compare all columns
4
#df1['exp1'] = (df1 < 0).sum(1)
5
print (df1)
6
b c d exp exp1
7
0 2 -2 -2 2 2
8
1 4 4 -4 1 1
9
2 1 1 1 0 0
10
3 1 -1 -1 2 2
11
4 2 2 2 0 0
12
5 5 5 5 0 0
13
6 -1 1 1 1 1
14
7 2 2 2 0 0
15
8 2 2 2 0 0
16
9 3 3 3 0 0
17
10 4 4 4 0 0
18
11 3 3 3 0 0
19
12 3 3 3 0 0
20
13 3 3 3 0 0
21