goscamp
goscamp

Reputation: 1106

Count categorical values in DataFrame

I have DataFrame only with Categorical Values

    Col1 | Col2| ... | ColM
Row
 1   X   |  Y  | ... |  X
 2   Z   |  X  | ... |  Y
 3   Y   |  Z  | ... |  X
 .
 .
 .
 N   X  |   Z  | ... | Z

I would like to count how many times each category appeared in database So example result:

X - 100 times
Y - 30 times
Z = 210 times

Thank You for help

Upvotes: 1

Views: 179

Answers (1)

cs95
cs95

Reputation: 402423

The most performant option is to use np.unique with the return_counts flag set:

u, c = np.unique(df, return_counts=True)
pd.Series(c, index=u)

There's also stack and value_counts, which is much slower, but simple and intuitive:

df.stack().value_counts()

Upvotes: 2

Related Questions