How to count no of rows in a data frame whose values divisible by 3 or 5?
Compare modulo 5
and 3
with 0
and filter by boolean indexing
with |
for bitwise OR
:
df = df[(df['ones'] % 5 == 0) | (df['zeros'] % 3 == 0)]
print (df)
ones zeros
5 10 6
6 11 6
9 4 6
13 14 3
26 6 12
29 9 9
4339 10 9
4342 4 6
4344 5 11
4345 7 9
4351 5 8
4352 5 7
4353 5 8
4355 11 3
4357 7 6
4358 8 12
4362 8 3
4364 9 3
4366 9 6
4368 4 3
If need to count number of matched values:
out = ((df['ones'] % 5 == 0) | (df['zeros'] % 3 == 0)).sum()
print (out)
20
We can also use the query
method to filter, combined with the pandas methods Series.mod
and eq
which stands for equal
:
df = df.query('ones.mod(5).eq(0) | zeros.mod(3).eq(0)')
ones zeros
5 10 6
6 11 6
9 4 6
13 14 3
26 6 12
29 9 9
30 10 9
33 4 6
35 5 11
36 7 9
42 5 8
43 5 7
44 5 8
46 11 3
48 7 6
49 8 12
53 8 3
55 9 3
57 9 6
59 4 3