Saved Bookmarks
| 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]]
Using combination of .diff(), .sign() and .where() method:
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]] |
|