Python - How to get the number of the most frequent values in a column?

Given a Pandas DataFrame, we have to get the number of the most frequent values in a column.
Submitted by Pranit Sharma, on August 20, 2022

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.

Get the number of the most frequent values in a column

To get the number of the most frequent value in a column, we will first access a column by using df['col_name'], and then we will apply the mode() method which will return the most frequent value.

Pandas dataframe.mode() returns the mode(s) of each element. It can be along the row or column. An important point is that there could be multiple values returned for the selected axis (when more than one value has the maximum frequency), and hence this returns a DataFrame as a whole.

Let us understand with the help of an example,

Python program to get the number of the most frequent values in a column

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'Col':[1,1,1,2,2,3,3,3,4,4]}

# Creating a DataFrame
df = pd.DataFrame(d)

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

# Using df[col].mode
result = df['Col'].mode()

# Display result
print("Mode:\n",result)

Output

The output of the above program is:

Example: Get the number of the most frequent values in a column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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