1.

How do you find the local peaks (or maxima) in a 1-D NumPy Array?

Answer»

Peaks are the points that are surrounded by smaller value points on either side as shown in the image below:

There are two ways of finding local maxima:

Using .where() method: This method lists all positions/indices where the element value at position i is greater than the element on either side of it. This method does not check for the points that have only one neighbour. This is demonstrated in the example below:

import numpy as np
# define NumPy array
arr = np.array([1, 4, 8, 1, 3, 5, 1, 6, 1, -5, -1, 19, 2])


maxima_peaks_positions = np.where((arr[1:-1] > arr[0:-2]) * (arr[1:-1] > arr[2:]))[0] + 1
print(maxima_peaks_positions)

Output:

[ 2 5 7 11]]

  • The +1 at the end of the expression is required as it finds the indexes within the slice arr[1:-1] and not the entire array arr.

  • The where() method returns a tuple of arrays where the first element is our required array. Hence we add [0] after the where method.

Using combination of .diff(), .sign() and .where() method:


  • In this method, we calculate the difference between each element using the diff() method of NumPy.

  • Then we use the sign() method on the array to get the sign of difference.

  • The value can be either -1 or +1. This result is then passed on to another diff() method which returns 0, -2 or +2 value. The value 0 indicates that the points are continuously increasing or decreasing, +2 indicates minimum peak and -2 indicates maximum peak (local maxima).

  • We then identify the position or indexes of the local maxima using the where() method. The reason for using +1 at the end of where and [0] after where is the same as the explanation described in Method 1 for finding local maxima.

The following code example demonstrates this:

import numpy as np
# define NumPy array
arr = np.array([1, 4, 8, 1, 3, 5, 1, 6, 1, -5, -1, 19, 2])

all_peaks = np.diff(np.sign(np.diff(arr)))
maxima_peaks_positions = np.where(all_peaks == -2)[0] + 1
print(maxima_peaks_positions)

Output:

[ 2 5 7 11]]


Discussion

No Comment Found