Question

I have a nested list a made of N sublists each of them filled with M floats. I have a way to obtain the index of the largest float using numpy, as shown in the MWE below:

import numpy as np

def random_data(bot, top, N):
    # Generate some random data.
    return np.random.uniform(bot, top, N)

# Generate nested list a.
N, M = 10, 7  # number of sublists and length of each sublist
a = np.asarray([random_data(0., 1., M) for _ in range(N)])

# x,y indexes of max float in a.
print np.unravel_index(a.argmax(), a.shape)

Note that I'm using the sublist index and the float index as x,y coordinates where x is the index of a sublist and y the index of the float inside said sublist.

What I need now is a way to find the coordinates/indexes of the largest float imposing certain boundaries. For example I would like to obtain the x,y values of the largest float for the range [3:5] in x and [2:6] in y.

This means I want to search for the largest float inside a but restricting that search to those sublists within [3:5] and in those sublists restrict it to the floats within [2:6].

I can use:

print np.unravel_index(a[3:5].argmax(), a[3:5].shape)

to restrict the range in x but the index returned is shifted since the list is sliced and furthermore I can think of no way to obtain the y index this way.

Was it helpful?

Solution

An alternative solution would be to set the values outside the range to be np.inf:

import numpy as np

# Generate nested list a.
N, M = 10, 7  # number of sublists and length of each sublist
a = np.random.rand(N, M)

# x,y indexes of max float in a.
print np.unravel_index(a.argmax(), a.shape)

A = np.full_like(a, -np.inf)  # use np.inf if doing np.argmin
A[3:5, 2:6] = a[3:5, 2:6]
np.unravel_index(A.argmax(), A.shape)

OTHER TIPS

You could turn 'a' into a matrix, which lets you easily index rows and columns. From there, the same basic command works to get the restricted indices. You can then add the start of the restricted indices to the result to get them in terms of the whole matrix.

local_inds = np.unravel_index(A[3:5,2:6].argmax(),A[3:5,2:6].shape)
correct_inds = np.asarray(local_inds) + np.asarray([3,2])

This won't work if you have more complicated index restrictions. If you have a list of the x and y indices you want to restrict by, you could do:

idx = [1,2,4,5,8]
idy = [0,3,6]
# make the subset of the data
b = np.asarray([[a[x][y] for y in idy] for x in idx])
# get the indices in the restricted data
indb = np.unravel_index(b.argmax(), b.shape)
# convert them back out
inda = (idx[indb[0]],idy[indb[1]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top