1

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?

bmello
  • 1,864
  • 3
  • 18
  • 23
  • `a.apply(pd.value_counts)` – Erfan Apr 05 '20 at 21:16
  • @Erfan, your comment is not what I asked, and you marked my question as a duplicate of a question that asks something different. Bruno Mello posted a proper answer. Could you please read again my question and the one you marked as a duplicate. – bmello Apr 05 '20 at 23:21

1 Answers1

3

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
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39
  • Thank you @Bruno Mello, it worked perfectly, although I had to change ```to_numpy()``` by ```values```, maybe because of the version of Pandas I am using. – bmello Apr 05 '20 at 23:23
  • Yes, it only works on versions >=0.24. I finally found a Brazilian here :) – Bruno Mello Apr 05 '20 at 23:31