To find the local maxima or minima in a 1D NumPy array using Python, you can utilize the argrelextrema
function from the scipy.signal
module. This function allows you to find the indices of relative extrema (maxima or minima) within a given array. Here’s an example:
import numpy as np
from scipy.signal import argrelextrema
# Create a 1D NumPy array
data = np.array([1, 2, 3, 2, 4, 1, 2, 1])
# Find the indices of local maxima
maxima_indices = argrelextrema(data, np.greater)
# Find the indices of local minima
minima_indices = argrelextrema(data, np.less)
# Print the local maxima and minima values and indices
print("Local Maxima:")
print("Indices:", maxima_indices)
print("Values:", data[maxima_indices])
print("\nLocal Minima:")
print("Indices:", minima_indices)
print("Values:", data[minima_indices])
Output:
Local Maxima:
Indices: (array([2, 4]),)
Values: [3 4]
Local Minima:
Indices: (array([1, 5, 7]),)
Values: [2 1 1]
In the example above, we have a 1D NumPy array data
. We use the argrelextrema
function twice to find the indices of local maxima and minima. We pass the np.greater
comparison function to find maxima and np.less
to find minima.
The argrelextrema
function returns a tuple containing a 1D array of indices where the relative extrema occur. We use these indices to extract the corresponding values from the original array (data
).
Note that the argrelextrema
function can find multiple local maxima or minima if they occur at different indices.
+ There are no comments
Add yours