简体   繁体   中英

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.

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

Something like this should help:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM