1

For example, I have a dataframe A likes below :

   a b c
x  0 2 1
y  1 3 2
z  0 2 4

I want to get the number of 0 in column 'a' , which should returns 2. ( A[x][a] and A[z][a] )

Is there a simple way or is there a function I can easily do this?

I've Googled for it, but there are only articles like this.

count the frequency that a value occurs in a dataframe column

Which makes a new dataframe, and is too complicated to what I only need to do.

HLM
  • 47
  • 7

2 Answers2

2

Use sum with boolean mask - Trues are processes like 1, so output is count of 0 values:

out = A.a.eq(0).sum()
print (out)
2
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Is this method suitable for dataframe? – HLM Oct 22 '19 at 09:34
  • @黃立銘 you can try it... if you wanted to get a count by column of how many zeros are present in each column, you could do `A[A == 0].sum()` for instance – Jon Clements Oct 22 '19 at 09:47
  • 1
    I try A.a.eq(0).sum() successfully, while (A['a'] == 0).sum() doesn't work. Still thank you a lot ! – HLM Oct 22 '19 at 10:57
-1

Try value_counts from pandas (here):

df.a.value_counts()["0"]

If the values are changeable, do it with df[column_name].value_counts()[searched_value]

emremrah
  • 1,733
  • 13
  • 19
  • This is definitely more expensive than simply indexing on the values which are `0` – yatu Oct 22 '19 at 09:26
  • A little overkill as this'll build a Series of all unique values and their counts only to just take a single value... – Jon Clements Oct 22 '19 at 09:26