Home >Backend Development >Python Tutorial >How to Find Local Maxima and Minima in a 1D Numpy Array Using SciPy?

How to Find Local Maxima and Minima in a 1D Numpy Array Using SciPy?

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 09:26:03237browse

How to Find Local Maxima and Minima in a 1D Numpy Array Using SciPy?

Finding Local Maxima/Minima in a 1D Numpy Array with Numpy

Identifying local maxima and minima in a 1D numpy array is a common task in signal processing and data analysis. While a simple approach involves comparing an element with its nearest neighbors, a more robust solution is sought within the numpy/scipy libraries.

Solution Using SciPy's argrelextrema

In SciPy versions 0.11 onwards, the argrelextrema function provides an efficient way to find local extrema in a 1D array:

import numpy as np
from scipy.signal import argrelextrema

x = np.random.random(12)

# Find indices of local maxima
maxima_indices = argrelextrema(x, np.greater)

# Find indices of local minima
minima_indices = argrelextrema(x, np.less)

The function returns tuples containing indices of elements that are local maxima or minima:

>>> argrelextrema(x, np.greater)
(array([1, 5, 7]),)
>>> argrelextrema(x, np.less)
(array([4, 6, 8]),)

To obtain the actual values at these local extrema:

>>> x[argrelextrema(x, np.greater)[0]]

Additional Functions in SciPy

In addition to argrelextrema, SciPy provides specialized functions for finding only maxima or minima:

  • argrelmax: Finds indices of local maxima
  • argrelmin: Finds indices of local minima

The above is the detailed content of How to Find Local Maxima and Minima in a 1D Numpy Array Using SciPy?. 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