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

import numpy as np

ar = np.array([5, 4, 2, 3, 4, 5, 7, 1, 0, 0, 1, 2, 1, 1])
n = np.bincount(ar).argmax()
print('The most frequent value in array:', n)
Output : 
The most frequent value in array: 1

Certainly! The provided Python code uses the NumPy library to find the most frequent (mode) value in an array. Here’s a detailed explanation of how the code works:

Explanation

  1. Import NumPy Library:
   import numpy as np
  • This line imports the NumPy library, which is a powerful library for numerical computing in Python.
  1. Create a NumPy Array:
   ar = np.array([5, 4, 2, 3, 4, 5, 7, 1, 0, 0, 1, 2, 1, 1])
  • This line creates a NumPy array ar with the specified elements.
  1. Calculate the Most Frequent Value:
   n = np.bincount(ar).argmax()
  • np.bincount(ar) counts the occurrence of each value in the array ar. The result is an array where the value at each index represents the count of that index in ar.
  • .argmax() returns the index of the maximum value in the array returned by np.bincount(ar). This index is the most frequent value in the original array ar.
  1. Print the Result:
   print('The most frequent value in array:', n)
  • This line prints the most frequent value in the array ar.

Example

Let’s go through the example provided:

  • Input Array:
  ar = np.array([5, 4, 2, 3, 4, 5, 7, 1, 0, 0, 1, 2, 1, 1])
  • Calculate Occurrence with np.bincount:
  • np.bincount(ar) returns an array [2, 4, 2, 1, 2, 2, 0, 1].
    • The index represents the value from the original array ar.
    • The value at each index represents how many times that index (value) appears in ar.
    • For example, 2 appears twice, 1 appears four times, and so on.
  • Find the Most Frequent Value:
  • .argmax() on [2, 4, 2, 1, 2, 2, 0, 1] returns 1 because 1 is the index of the maximum value 4.
  • Result:
  The most frequent value in array: 1

Summary

This code uses the NumPy library to find the most frequent value in a given array. The np.bincount function counts the occurrences of each value in the array, and argmax finds the index of the highest count, which corresponds to the most frequent value in the original array. The result is then printed.

Leave a Reply

Your email address will not be published. Required fields are marked *