HLM
HLM

Reputation: 47

How to find the number of an element in a column of a dataframe

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.

Upvotes: 1

Views: 90

Answers (2)

jezrael
jezrael

Reputation: 862601

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

Upvotes: 2

emremrah
emremrah

Reputation: 1765

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]

Upvotes: -1

Related Questions