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
Release: 2024-11-15 09:26:03
Original
195 people have browsed it

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:

1

2

3

4

5

6

7

8

9

10

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)

Copy after login

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

1

2

3

4

>>> argrelextrema(x, np.greater)

(array([1, 5, 7]),)

>>> argrelextrema(x, np.less)

(array([4, 6, 8]),)

Copy after login

To obtain the actual values at these local extrema:

1

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

Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template