Nathaniel Mackinlay
Nathaniel Mackinlay

Reputation: 9

Python/Pandas: How to find the number of occurrences of a specific value in each column a data frame?

So I have a dataframe that has 300 columns and thousands of rows. Each column contains a value between 0-30. I am trying, to find the total number of times that the number 8 occurs in each column.

Ideally, I'm trying to create a list of length 300 with each index corresponding to the index of the column, with a value corresponding to the number of rows that contain the number 8 in that column.

Any help or guidance is appreciated, thank you.

Upvotes: 0

Views: 73

Answers (2)

codemaster
codemaster

Reputation: 31

Something like this should help:

df.isin([8]).sum(axis=0)

Upvotes: 0

user15398259
user15398259

Reputation:

You can use a boolean test and .sum()

>>> df
   a  b  c  d
0  8  6  7  8
1  8  8  7  6
2  1  2  3  4

>>> df == 8
       a      b      c      d
0   True  False  False   True
1   True   True  False  False
2  False  False  False  False

>>> (df == 8).sum()
a    2
b    1
c    0
d    1
dtype: int64

Upvotes: 2

Related Questions