Finding the Most Frequent Value

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

Example 1:

Input: np.array([1, 2, 3, 2, 2, 4, 3, 4, 2, 5]) 
Output: 2

Example 2:

Input: np.array([10, 10, 20, 20, 20, 30, 30, 30, 30]) 
Output: 30

You can use np.bincount() and np.argmax() functions to find the most frequent value in an array.

import numpy as np

def find_frequent(array):
    counts = np.bincount(array)
    return np.argmax(counts)

print(find_frequent(np.array([1, 2, 3, 2, 2, 4, 3, 4, 2, 5])))
print(find_frequent(np.array([10, 10, 20, 20, 20, 30, 30, 30, 30])))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!