Mode of NumPy Array in Python (2 Examples)


In this tutorial, I’ll show how to calculate the mode of a NumPy array in the Python programming language.

Table of contents:

Let’s get started:


Example Data & Libraries

In order to use the functions of the NumPy library, we first have to load NumPy:

import numpy as np                          # Load NumPy library

Furthermore, we have to import stats from the SciPy library:

from scipy import stats

Now, we can create an example array as shown below:

my_array = np.array([[1, 5, 2, 2, 1, 6],    # Create example array
                     [7, 2, 3, 1, 8, 6],
                     [1, 3, 4, 2, 7, 1],
                     [1, 3, 2, 2, 8, 5]])
print(my_array)                             # Print example array
# [[1 5 2 2 1 6]
#  [7 2 3 1 8 6]
#  [1 3 4 2 7 1]
#  [1 3 2 2 8 5]]

Have a look at the previous output of the Python console. It shows that our example array contains 24 values in four rows and six columns.


Example 1: Mode of Columns in NumPy Array

The following Python programming code illustrates how to calculate the mode of each column in our NumPy array.

For this task, we can apply the mode function as shown in the following Python code:

print(stats.mode(my_array)[0])              # Get mode of array columns
# [[1 3 2 2 8 6]]

As you can see, the previous syntax has returned the mode value of each column in our example array.


Example 2: Mode of Columns in NumPy Array

In Example 2, I’ll demonstrate how to find the mode of a NumPy array by row.

For this, we have to set the axis argument within the mode function to 1:

print(stats.mode(my_array, axis = 1)[0])    # Get mode of array rows
# [[1]
#  [1]
#  [1]
#  [2]]


Video & Further Resources

Would you like to know more about the calculation of the mode of a NumPy array? Then I recommend having a look at the following video that I have published on my YouTube channel. I’m illustrating the Python codes of this post in the video:



In addition, you might want to have a look at the other articles which I have published on Statistics Globe:


In this post you have learned how to find the mode of a NumPy array in Python. Let me know in the comments below, if you have further questions.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.