0

I am trying to count uniqiue values that are in few columns. My data frame looks like that:

Name      Name.1    Name.2    Name.3
x         z          c          y
y         p          q          x
q         p           a         y

Output should looks like below:

x   2
z   1
c   1
y   3
q   2
p   2
a   1

I used a groupby or count_values but couldn't get a correct output. Any ideas ? Thanks All !

Tmiskiewicz
  • 389
  • 1
  • 11
  • you can simply stack and count i.e `df.stack().value_counts()` – Bharath M Shetty Jan 27 '19 at 13:21
  • 1
    Possible duplicate of [Get total values\_count from a dataframe with Python Pandas](https://stackoverflow.com/questions/52018311/get-total-values-count-from-a-dataframe-with-python-pandas). Also contains timings which may be relevant for your object type `DataFrame` – ALollz Jan 27 '19 at 17:01

2 Answers2

2

Seems you want to consider values regardless of their row or column location. In that case you should collapse the dataframe and just use Counter.

from collections import Counter

arr = np.array(df)
count = Counter(arr.reshape(arr.size))
kentwait
  • 1,969
  • 2
  • 21
  • 42
0

Another (Pandas-based) approach is to (Series) apply value_counts to multiple columns and then take the sum (column-wise)

df2 = df.apply(pd.Series.value_counts)
print(df2.sum(axis=1).astype(int)
a    1
c    1
p    2
q    2
x    2
y    3
z    1
dtype: int32
edesz
  • 11,756
  • 22
  • 75
  • 123