I have two dataframe columns containing sequences of 0 and -1. Using Python command “count” I can calculate the number of times the 1st column equal '-1' ( =3 times) and the number of times the 2nd column equals '-1' ( =2 times). Actually, I would like to calculate the number of times that both columns x and y are equal to '-1' simultaneously ( = it should be equal to 1 in the given example)(something like calculating: count = df1['x'][df1['x'] == df1['y'] == -1]. count() but I cannot put 2 conditions directly in command 'count'..). Is there a simpe way to do it (using count or some other workaround)? Thanks in advance!
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
df1 = pd.DataFrame({
"x": [0, 0, 0, -1 , 0, -1, 0, 0, 0, 0 , 0, 0, 0, -1, 0],
"y": [0, 0, 0, 0 , 0, 0, -1, 0, 0, 0 , 0, 0, 0, -1, 0],
})
df1
x y
0 0 0
1 0 0
2 0 0
3 -1 0
4 0 0
5 -1 0
6 0 -1
7 0 0
8 0 0
9 0 0
10 0 0
11 0 0
12 0 0
13 -1 -1
14 0 0
count = df1['x'][df1['x'] == -1]. count()
count
3
count = df1['y'][df1['y'] == -1]. count()
count
2
CodePudding user response:
You can use eq
all
to get a boolean Series that returns True if both columns are equal to -1 at the same time. Then sum
fetches the total:
out = df1[['x','y']].eq(-1).all(axis=1).sum()
Output:
1
CodePudding user response:
Sum x
and y
, and count the ones where they add to -2. ie both are -1
(df1.x df1.y).eq(-2).sum()
1