Numpy is the best python package for doing complex mathematical calculations. It has many functions for array creation and manipulation. In this entire tutorial, you will know how to find a mode of a NumPy array in python using various examples.
What is a Mode?
A mode is generally used to find the most occurrences of the data points in a dataset. Datasets can have one mode, two-mode, or no mode at all.
Examples to Find mode for Numpy array
In this section, you will know the various examples of how to find a mode of an array. However you can use your own numeric datasets, but for simplicity, I am finding mode in a sample NumPy array. Make sure you must have properly installed NumPy in your system.
Example 1: Find mode on 1 D Numpy array
In this example, I will find mode on a single-dimensional NumPy array. First I will create a Single dimension NumPy array and then import the mode() function from scipy. Execute the below lines of code to calculate the mode of 1d array.
import numpy as np
from scipy import stats
array_1d = np.array([1,2,3,2,4,5,5,5])
print(stats.mode(array_1d))
Output
Here you can see the occurrence of 5 is more than any other elements. That’s why this array has mode 5.
Example 2: Finding mode on 2 D Numpy array
In the next example, I will create two dimensional NumPy array and use the stats.mode() method on that array. There are two ways you can find mode on a 2D Numpy array. One is finding mode for each row-wise and the other is finding mode on entire array. Let’s explore each of them.
Finding mode rowwise
To find mode rowise you have to set the axis as zero value. It will find the array of modes for each column. Run the below lines of code and see the output.
import numpy as np
from scipy import stats
array_2d = np.array([[1,2,3],[1,5,6],[1,2,10]])
print(stats.mode(array_2d))
Output
Finding Overall Mode
In the same way, you can find mode for the entire array. To do so you have to set the axis value as None. Just execute the below lines of code and see the output.
import numpy as np
from scipy import stats
array_2d = np.array([[1,2,3],[1,5,6],[1,2,10]])
print(stats.mode(array_2d,axis=None))
Output
Conclusion
Mode is very useful for finding the measure of the central tendency. You can use it for finding the standard deviation of the dataset. These are the basic example for finding a mode of the array in python. I hope you have liked this tutorial. If you have any questions then you can contact us for more help. In the meantime, you can subscribe to us for quick updates directly in your inbox.
Source:
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.