+3 votes
in Programming Languages by (74.2k points)
edited by
How to count the number of elements that are less than a particular value in each column of a pandas dataframe?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Here are the things you need to do to count the number of elements that are less than 'N' in each column.

  • Get the list of columns.
  • Use those columns on the dataframe to check the values in those columns.
  • Then apply the count() function to count the number.

Check the following example:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'a':np.random.permutation(20), 'b':np.random.permutation(20), 'c':np.random.permutation(20)})
>>> df
     a   b   c
0   16   3   0
1    5  15  11
2    1  13  19
3    2   1   3
4   13   7   4
5   14  17   5
6   10   8  12
7    0   4   8
8    3   9   7
9    4  16  15
10   6   0  10
11  15   2   1
12  12  10   2
13  18  14   9
14   8  12   6
15   9   5  13
16  19  19  14
17   7  18  18
18  17   6  16
19  11  11  17

>>> df[df[df.columns] <10]
      a    b    c
0   NaN  3.0  0.0
1   5.0  NaN  NaN
2   1.0  NaN  NaN
3   2.0  1.0  3.0
4   NaN  7.0  4.0
5   NaN  NaN  5.0
6   NaN  8.0  NaN
7   0.0  4.0  8.0
8   3.0  9.0  7.0
9   4.0  NaN  NaN
10  6.0  0.0  NaN
11  NaN  2.0  1.0
12  NaN  NaN  2.0
13  NaN  NaN  9.0
14  8.0  NaN  6.0
15  9.0  5.0  NaN
16  NaN  NaN  NaN
17  7.0  NaN  NaN
18  NaN  6.0  NaN
19  NaN  NaN  NaN

>>> df[df[df.columns] <10].count()
a    10
b    10
c    10

Here all the columns have ten elements that are less than 10.


...