According the NumPy tutorial, the correct way to do it is:
a[tuple(b)]
Answer from JoshAdel on Stack Overflowpython - Indexing numpy array with another numpy array - Stack Overflow
python - Index of element in NumPy array - Stack Overflow
Indexing a np.array with another np.array
Numpy array of Decimal objects for efficient indexing or other basic operations?
Videos
According the NumPy tutorial, the correct way to do it is:
a[tuple(b)]
Suppose you want to access a subvector of a with n index pairs stored in blike so:
b = array([[0, 0],
...
[1, 1]])
This can be done as follows:
a[b[:,0], b[:,1]]
For a single pair index vector this changes to a[b[0],b[1]], but I guess the tuple approach is easier to read and hence preferable.
Use np.where to get the indices where a given condition is True.
Examples:
For a 2D np.ndarray called a:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
For a 1D array:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
Note that this also works for conditions like >=, <=, != and so forth...
You can also create a subclass of np.ndarray with an index() method:
class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
Testing:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
You can convert a numpy array to list and get its index .
for example:
tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1
this is just what you wanted.
Indexing one array with another array has different behavior than if I index with the same array without explicitly casting it to a numpy array first (i.e. I leave it as a list of lists). I can't find the pages in the documentation that explain this kind of indexing
Example:
#make a 5x5 matrix for testing, the numbers arent important
a = np.random.rand(5,5)
#another arbitrary 5x5 matrix
b = [[0, 0, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 1, 1, 0],
[0, 1, 1, 0, 0],
[1, 1, 0, 0, 0]]
c = np.array(b)
a[b] #gives the error "too many indices for array: array is 2-dimensional, but 5 were indexed"
a[tuple(c)] #gives the same error as a[b]
a[c] #for some reason this works, and it returns a 5x5x5 matrix So the behavior changes when I convert the list of lists to a numpy array. And I can't really tell what it's doing by looking at the output of a[c]. It seems to be switching the rows around somehow but I'm confused at why it returns five copies of the original matrix. Is there any page in the documentation that describes this type of indexing?