How to Calculate the Mode of NumPy Array?
Last Updated :
12 Jan, 2022
In this article, we will discuss how to calculate the mode of the Numpy Array.
Mode refers to the most repeating element in the array. We can find the mode from the NumPy array by using the following methods.
Method 1: Using scipy.stats package
Let us see the syntax of the mode() function
Syntax :
variable = stats.mode(array_variable)
Note : To apply mode we need to create an array. In python, we can create an array using numpy package. So first we need to create an array using numpy package and apply mode() function on that array. Let us see examples for better understanding.
Example 1:
Applying on 1-D array
Python3
from scipy import stats as st
import numpy as np
abc = np.array([ 1 , 1 , 2 , 2 , 2 , 3 , 4 , 5 ])
print (st.mode(abc))
|
Output :
ModeResult(mode=array([2]), count=array([3]))
Example 2:
Applying on a 2-D array
Python3
import numpy as np
from scipy import stats as st
arr = np.array([[ 1 , 2 , 3 , 4 , 5 ],
[ 1 , 2 , 2 , 2 , 2 ],
[ 4 , 5 , 7 , 9 , 4 ],
[ 6 , 7 , 8 , 9 , 2 ],
[ 2 , 3 , 4 , 8 , 6 ]])
print (st.mode(arr))
|
Output :
ModeResult(mode=array([[1, 2, 2, 9, 2]]), count=array([[2, 2, 1, 2, 2]]))
Method 2: Using Statistics module
Like NumPy module, the statistics module also contains statistical functions like mean , median , mode….etc . So let us see an example of a mode using the statistics module.
Example :
Python3
import statistics as st
import numpy as np
arr1 = np.array([ 9 , 8 , 7 , 6 , 6 , 6 , 6 , 5 , 5 , 4 ,
3 , 2 , 1 , 1 , 1 , 1 , 1 , 1 ])
print (st.mode(arr1))
|
Output :
1
Method 3: Using user-defined Function
Here we are not using any predefines functions for getting mode of a series. Let us see an example with demonstrates how to calculate mode without predefined functions.
Example :
Python3
lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 2 , 3 , 4 , 5 , 5 , 5 , 5 ]
def mode(lst):
freq = {}
for i in lst:
freq.setdefault(i, 0 )
freq[i] + = 1
hf = max (freq.values())
hflst = []
for i, j in freq.items():
if j = = hf:
hflst.append(i)
return hflst
print (mode(lst))
|
Output :
[5]
Share your thoughts in the comments
Please Login to comment...