Mode Function in Python pandas (Dataframe, Row and column wise mode)

Mode Function in python pandas is used to calculate the mode or most repeated value of a given set of numbers. Mode of a data frame, mode of column and mode of rows, let’s see an example of each We need to use the package name “statistics” in calculation of mode. In this tutorial we will learn,

  • How to find the mode of a given set of numbers
  • How to find mode of a dataframe
  • How to find the mode of a column in dataframe
  • How to find row mode of a dataframe

Mode Function in Python pandas

Simple mode function in python is shown below

# calculate mode or most repeated value
Import statistics

print(statistics.mode([1,5,5,7,5,6,8,7]))
print(statistics.mode(['lion', 'cat', 'cat','dog','tiger']))

output:

5
cat

 

Mode of a dataframe:

Create dataframe


import pandas as pd
import numpy as np

#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine',
   'Rahul','David','Andrew','Ajay','Teresa'],
   'Score1':[62,47,55,74,47,77,85,63,42,32,71,57],
   'Score2':[89,87,67,55,47,72,76,79,44,67,99,69],
   'Score3':[56,86,77,45,73,62,74,89,71,67,97,68]}



df = pd.DataFrame(d)
df

So the resultant dataframe will be

mode function in python 1

Mode of the dataframe:


# mode of the dataframe
df.mode()

will calculate the mode of the dataframe across columns so the output will be

mode function in python 2

 

Column Mode of the dataframe in python pandas :


# column mode of the dataframe
df.mode(axis=0)

axis=0 argument calculates the column wise mode of the dataframe so the result will be

mode function in python 3

 

Row Mode of the dataframe in python pandas :


# Row mode of the dataframe
df.mode(axis=1)

axis=1 argument calculates the row wise mode of the dataframe so the result will be

mode function in python 4

 

Calculate the mode of the specific Column – pandas


# mode of the specific column
df.loc[:,"Score1"].mode()

the above code calculates the mode of the “Score1” column so the result will be

0  47
dtype: int64

 

previous-small mode function in python pandas                                                                                                                next_small mode function in python pandas