w3resource

NumPy: Find the most frequent value in an array

NumPy: Random Exercise-13 with Solution

Write a NumPy program to find the most frequent value in an array.

Sample Solution:

Python Code:

# Importing the NumPy library as np
import numpy as np

# Generating a random array 'x' with integers between 0 and 10 (exclusive) having 40 elements
x = np.random.randint(0, 10, 40)

# Displaying the original array 'x'
print("Original array:")
print(x)

# Finding the most frequent value in the array using np.bincount() to count occurrences
# Then using argmax() to find the index of the maximum count, which represents the most frequent value
most_frequent_value = np.bincount(x).argmax()

# Displaying the most frequent value in the array
print("Most frequent value in the above array:")
print(most_frequent_value)

Sample Output:

Original array:                                                        
[4 7 3 8 4 8 6 3 1 8 6 3 3 9 7 8 3 3 0 6 8 3 1 8 2 2 9 7 8 9 8 5 9 6 8 
5 3                                                                    
 8 9 1]                                                                
Most frequent value in the above array:                                
8 

Explanation:

In the above example –

x = np.random.randint(0, 10, 40): This line generates an array of 40 random integers between 0 (inclusive) and 10 (exclusive) using the np.random.randint() function.

np.bincount(x).argmax():

In the above code –

  • np.bincount(x): This function counts the number of occurrences of each non-negative integer in the array x. It returns an array where the element at index i represents the count of the integer i in the input array x. For example, if x contains five occurrences of the integer 3, the element at index 3 in the output array would be 5.
  • np.bincount(x).argmax(): This function finds the index of the maximum element in the output array of np.bincount(x). Since the indices of the output array represent the integers in x, this index corresponds to the most frequent integer in the array x.

Pictorial Presentation:

NumPy Random: Find the most frequent value in an array.

Python-Numpy Code Editor:

Previous: Write a NumPy program to find point by point distances of a random vector with shape (10,2) representing coordinates.
Next: Write a NumPy program to convert cartesian coordinates to polar coordinates of a random 10x3 matrix representing cartesian coordinates.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.