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

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

Mary-Kate Olsen
Release: 2024-11-13 17:18:02
Original
683 people have browsed it

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

Utilizing Numpy's SciPy Module to Locate Local Maxima and Minima in a 1D Numpy Array

Seeking a Numpy or SciPy module function capable of identifying local maxima and minima within a 1D Numpy array, we can explore a proven solution employed within the Numpy distribution.

Solution Using SciPy's Extrema Detection Functions

For instances where your SciPy installation is version 0.11 or later, you can leverage the argrelextrema function:

import numpy as np
from scipy.signal import argrelextrema

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

This script generates arrays containing the indices of local maxima or minima. To retrieve the corresponding values, utilize:

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

Alternative Options from SciPy.Signal

SciPy.signal also offers dedicated functions for handling max and min detection:

  • argrelmax: Locates local maxima
  • argrelmin: Locates local minima

Employ these methods for specific extraction of maxima or minima.

Example Output

For the example array [0.56660112, 0.76309473, 0.69597908, 0.38260156, 0.24346445, 0.56021785, 0.24109326, 0.41884061, 0.35461957, 0.54398472, 0.59572658, 0.92377974], the output indices of local maxima and minima are:

  • Maxima: [1, 5, 7]
  • Minima: [4, 6, 8]

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