Pandas Tutorial Pandas References

Pandas Series - mode() function

The Pandas Series mode() function returns the mode(s) of the series. The syntax for using this function is mentioned below:




dropna Optional. Specify True to exclude NA/null values when computing the result. Default is True.

Return Value

Returns mode(s) of the Series in sorted order.

Example: using mode() on a Series

In the example below, the mode() function is used to get the mode of values of a given series.

import pandas as pd
import numpy as np

idx = pd.MultiIndex.from_arrays([
    ['even', 'even', 'even', 'even', 
     'odd', 'odd', 'odd', 'odd']],

x = pd.Series([10, 20, 20, 30, 5, 5, 7, 9], 
              name='Numbers', index=idx)

print("The Series contains:")

#mode of all values in the series
print("\nx.mode() returns:")

The output of the above code will be:

The Series contains:
even    10
even    20
even    20
even    30
odd      5
odd      5
odd      7
odd      9
Name: Numbers, dtype: int64

x.mode() returns:
0     5
1    20
dtype: int64

Example: using mode() on selected series in a DataFrame

Similarly, the mode() function can be applied on selected series/column of a given DataFrame. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4],
  "Last Salary": [58, 60, 63, 57],
  "Salary": [62, 62, 65, 59]},
  index= ["John", "Marry", "Sam", "Jo"]

print("The DataFrame is:")

#mode of all values of 'Salary' series
print("\ndf['Salary'].mode() returns:")

The output of the above code will be:

The DataFrame is:
       Bonus  Last Salary  Salary
John       5           58      62
Marry      3           60      62
Sam        2           63      65
Jo         4           57      59

df['Salary'].mode() returns:
0    62
dtype: int64

❮ Pandas Series - Functions