+4 votes
in Programming Languages by (9.6k points)
I want to find the local minima and maxima in a given list. Is there any Python function that I can use for it?

1 Answer

+2 votes
by (42.1k points)

There are functions in scipy.signal module that can be used to find local minima and maxima in an array/matrix.

Function argrelmin() is used to calculate the relative minima of data. Similarly, argrelmax() is used to calculate the relative maxima of data. These functions return the indices of local minima/maxima in the data. The indices can be used to find the values of local minima/maxima.

The following example shows how to use these functions. I am also plotting the data so that the local minima/maxima can be verified visually.

import numpy as np
from scipy.signal import argrelmin, argrelmax
import matplotlib.pyplot as plt

# generate random data
y = np.random.random_sample(25)
x = np.asarray([i+1 for i in range(25)])

# find local minima and maxima
min_idx = argrelmin(y)
print("Indices of minima: {0}".format(min_idx))
print("Minima: {0}".format(y[min_idx]))

max_idx = argrelmax(y)
print("Indices of maxima: {0}".format(max_idx))
print("Maxima: {0}".format(y[max_idx]))

# plot data
plt.plot(x, y, 'g-o')

The above code prints the following output:

Indices of minima: (array([ 2,  7, 13, 16, 19, 22]),)
Minima: [0.43840923 0.07205113 0.06593635 0.21338535 0.02489923 0.23030288]
Indices of maxima: (array([ 1,  4, 11, 15, 18, 21]),)
Maxima: [0.77991879 0.97798951 0.80373904 0.90959353 0.93120602 0.9501295 ]

It generates the following plot. You can verify the results by looking at the plot.Local maxim and minima