Let say I have an array:
x = np.array([7., 5., 4., 1., 9., 2., 3., 6.,])
For each index, I want to find the argmin to the right of that index and also the argmin to the left of that index. Endpoints will have an an argmin of -1 when there is no index value available, so, the outputs would be:
left_argmins = [-1, 0, 1, 2, 3, 3, 3, 3]
right_argmins = [3, 3, 3, 5, 5, 6, 7, -1]
A naive approach (but slow approach) would be:
right_argmins = np.full(len(x), -1)
for i in range(len(x)):
min_val = np.inf
idx = -1
for j in range(i+1, len(x)):
if x[j] < min_val:
min_val = x[j]
idx = j
right_argmins[i] = idx
left_argmins = np.full(len(x), -1)
for i in range(len(x)):
min_val = np.inf
idx = -1
for j in range(i):
if x[j] < min_val:
min_val = x[j]
idx = j
left_argmins[i] = idx
What's the best way to accomplish this in NumPy?
Additionally, what would I do if I needed to do this for a 2D array?