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

Learn, how to get value counts for multiple columns at once in Pandas DataFrame? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose that we are given a Pandas DataFrame that has multiple columns with categorical values (0 or 1), we need to find a way to get the value counts for every column at the same time.

Getting value counts for multiple columns at once

For this purpose, we will use the pandas apply() method inside which we will use the series value_counts() method. This method returns a Series that contain counts of unique values.

Let us understand with the help of an example,

Python program to get value counts for multiple columns at once in Pandas DataFrame

# Import numpy
import numpy as np

# Import pandas
import pandas as pd

# Creating a dataframe
df = pd.DataFrame(np.arange(1,10).reshape(3,3))

# Display original dataframe
print("Original DataFrame:\n",df,"\n")

# Counting values of a column
res = df.apply(pd.Series.value_counts)

# Display new df
print("Values:\n",res,"\n")

Output

The output of the above program is:

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

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.