Home > Backend Development > Python Tutorial > How can SciPy's `argrelextrema` function be used to effectively detect local maxima and minima in 1D Numpy arrays?

How can SciPy's `argrelextrema` function be used to effectively detect local maxima and minima in 1D Numpy arrays?

Susan Sarandon
Release: 2024-11-16 07:04:02
Original
567 people have browsed it

How can SciPy's `argrelextrema` function be used to effectively detect local maxima and minima in 1D Numpy arrays?

Local Extrema Detection in 1D Numpy Arrays with SciPy

Finding local maxima and minima in 1D numerical arrays is a common task in data analysis. While simplistic approaches might involve comparing an element to its neighbors, it is advisable to use established algorithms as part of popular scientific computing libraries.

One such library is SciPy, which offers the argrelextrema function for locating local extrema in 1D arrays. This function can work with both maxima and minima, making it a versatile solution. Here's how to use it:

import numpy as np
from scipy.signal import argrelextrema

# Example 1D array
x = np.random.random(12)

# Detect local maxima
maxima_indices = argrelextrema(x, np.greater)

# Detect local minima
minima_indices = argrelextrema(x, np.less)
Copy after login

The argrelextrema function returns a tuple containing an array with the indices of local extrema. Note that these are just the indices in the input array, not the actual values. To obtain the corresponding values, use:

maxima_values = x[maxima_indices[0]]
minima_values = x[minima_indices[0]]
Copy after login

For convenience, SciPy also provides the standalone functions argrelmax and argrelmin for finding maxima and minima separately.

The above is the detailed content of How can SciPy's `argrelextrema` function be used to effectively detect local maxima and minima in 1D Numpy arrays?. 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