Reputation: 45
I want to find all the maximums and their index in a numpy array.
I am looking for something simple. I started something like data[1:] < data[:-1] no idea how to get 20 and 30 and their index 2 and 7.
import numpy as np
data = np.array([0,1,20,1,0,1,2,30,2,1,0])
A = data[1:] < data[:-1]
EDIT: Argmax and findpeaks sound difficult (find peaks gives you min and max for instance). I did a np.diff and a loop and I have my index eventhough I try to avoid using loop
import numpy as np
def maximum_index(data):
data = np.diff(data)
index_max = []
for index in range(len(data)-1):
if data[index] > 0 and data[index+1] < 0:
index_max.append(index+1)
return np.asarray(index_max)
data = np.array([0,1,9,1,0,1,2,9,2,1,0])
result_max = maximum_index(data)
Thank you
Upvotes: 1
Views: 168
Reputation: 827
You can use numpy.argsort as follows:
import numpy as np
data = np.array([0,1,20,1,0,1,2,30,2,1,0])
N = 2 # number of maxima
idx = np.argsort(data)[-N:]
idx
array([2, 7], dtype=int64)
data[idx]
array([20, 30])
If you don't know the number of maxima, you can use scipy.signal.find_peaks:
from scipy.signal import find_peaks
idx = find_peaks(data)[0]
idx
array([2, 7], dtype=int64)
data[idx]
array([20, 30])
Upvotes: 2
Reputation: 1446
you can try below code
max_data_pos=np.argmax(data) #Find position of max elelemt
max_data_val=data[max_data_pos] #Find Max Valuse
second_max_data_pos=np.argmax(np.delete(data,max_data_pos)) #Find position of second max elelemt
secondmax_data_val=data[second_max_data_pos] #Find Max Valuse
Upvotes: 0