How to apply value_counts to all elments of a DataFrame?

It is easy to apply value_counts to a Series:

In [1]: import pandas as pd

In [2]: a = pd.DataFrame([[2,3],[2,2],[3,2],[2,1]])

In [3]: a
Out[3]: 
   0  1
0  2  3
1  2  2
2  3  2
3  2  1

In [4]: a[0].value_counts()
Out[4]: 
2    3
3    1
Name: 0, dtype: int64

I need something like

In [5]: a.value_counts()
Out[5]: 
2    5
3    2
1    1
dtype: int64

However, a.value_counts() returns 'DataFrame' object has no attribute 'value_counts'.

How could I apply value_counts to the element of a DataFrame?

1 answer

  • answered 2020-04-05 21:16 Bruno Mello

    You can transform to numpy, flat the data and then change it again to a pandas series:

    pd.Series(a.to_numpy().reshape(-1)).value_counts()
    
    2    5
    3    2
    1    1
    dtype: int64