How can i count a value in all of data frame?

Viewed 47

I want to count an specific value in all of the data frame.
for example, we have a data frame like this:

df = pd.DataFrame({
    0 : ["a", "b", "a"],
    1 : ["c", "a", "b"],
    2 : ["c", "b", "b"]
})
>>> df
0 1 2
0 a c c
1 b a b
2 a b b

I want this result :

a 3
b 4
c 2

any body know, how can i do it ?!
thanks

3 Answers

You could use value_counts method, but use stack before calling this method.

df.stack().value_counts()
>>>
b    4
a    3
c    2

You can stack and value_counts:

df.stack().value_counts()

Output:

b    4
a    3
c    2
dtype: int64

Different answer:

df = pd.DataFrame({
    0 : ["a", "b", "a"],
    1 : ["c", "a", "b"],
    2 : ["c", "b", "b"]
})
df1 = pd.melt(df, value_vars=[0,1,2],var_name='colName',value_name='value').groupby('value').count()
print(df1)



colName value         
a            3
b            4
c            2
Related