Find the most frequent value in a NumPy array

Learn, how to find the most frequent value in a NumPy array? By Pranit Sharma Last updated : October 08, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Mathematically, the most frequent value in a number series is called its mode. Here, we are given a NumPy array and we need to find the most frequent element in this NumPy array.

Finding the most frequent value in a NumPy array

For this purpose, we will first use the counter() method of the collections library and then we will apply the most_common() attribute of the counter() method.

Let us understand with the help of an example,

Python program to find the most frequent value in a NumPy array

# Import counter from collections
from collections import Counter

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([1,2,3,1,2,1,1,1,3,2,2,1])

# Display original array
print("Original Array:\n",arr,"\n")

# count values
count = Counter(arr)

# Most frequent value
res = count.most_common(1)

# Display result
print("Most frequent value:\n",res,"\n")

Output

The output of the above program is:

Example: Find the most frequent value in a NumPy array

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.