Skip to content
Advertisement

How to get value counts for multiple columns at once in Pandas DataFrame?

Given a Pandas DataFrame that has multiple columns with categorical values (0 or 1), is it possible to conveniently get the value_counts for every column at the same time?

For example, suppose I generate a DataFrame as follows:

JavaScript

I can get a DataFrame like this:

JavaScript

How do I conveniently get the value counts for every column and obtain the following conveniently?

JavaScript

My current solution is:

JavaScript

But there must be a simpler way, like stacking, pivoting, or groupby?

Advertisement

Answer

Just call apply and pass pd.Series.value_counts:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement