Pandas DataFrame mode() Method

5/5 - (1 vote)


Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.

Feel free to view the PyCharm installation guide for the required libraries.

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame mode()

The mode() method determines the most commonly used numbers in a DataFrame/Series.

The syntax for this method is as follows:

DataFrame.mode(axis=0, numeric_only=False, dropna=True)
axisIf zero (0) or index is selected, apply to each column. Default 0.
If one (1) apply to each row.
numeric_onlyOnly include columns that contain integers, floats, or boolean values.
dropnaIf set to True, this parameter ignores all NaN and NaT values. By default, this value is True.

For this example, we determine the numbers that appear more than once.

df_teams = pd.DataFrame({'Bruins':    [4, 5,  9],
                         'Oilers':    [3, 9, 13],
                         'Leafs':     [2, 7, 4],
                         'Flames':    [13, 9, 7]})

result = df_teams.mode(axis=0)
  • Line [1] creates a DataFrame from a Dictionary of Lists and saves it to df_teams.
  • Line [2] uses the mode() method across the column axis. This output saves to the result variable.
  • Line [3] outputs the result to the terminal.



You can see where the numbers come from in this visualization:

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.