Home >Backend Development >Python Tutorial >How to Find Local Maxima and Minima in 1D Numpy Arrays?

How to Find Local Maxima and Minima in 1D Numpy Arrays?

DDD
DDDOriginal
2024-11-19 21:56:02983browse

How to Find Local Maxima and Minima in 1D Numpy Arrays?

Locating Local Maxima and Minima in 1D Arrays with Numpy

Identifying local maxima and minima in 1D numpy arrays is a common task in various applications. While checking adjacent elements is an intuitive approach, Numpy offers a more comprehensive and reliable solution.

Numpy's argrelextrema Function

In SciPy 0.11 and later, the argrelextrema function can efficiently find both local maxima and minima in a 1D numpy array. It takes two arguments:

  1. array: The input numpy array.
  2. comparator: A comparison function (e.g., np.greater or np.less) that specifies the criteria for identifying extrema.

Usage:

To find local maxima, use:

argrelextrema(x, np.greater)

To find local minima, use:

argrelextrema(x, np.less)

Output

The argrelextrema function returns a tuple containing a single-dimensional array of indices corresponding to the extrema. These indices can be used to access the values of the local maxima or minima.

Example:

Consider the following numpy array:

x = np.random.random(12)

Finding the indices of local maxima and minima:

max_indices = argrelextrema(x, np.greater)[0]
min_indices = argrelextrema(x, np.less)[0]

Retrieving the actual values:

max_values = x[max_indices]
min_values = x[min_indices]

By using Numpy's argrelextrema function, you can accurately identify local maxima and minima in 1D numpy arrays, simplifying this common task.

The above is the detailed content of How to Find Local Maxima and Minima in 1D Numpy Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn