get value from tensor by using index array python

Question:

I have an array A :

A = [[1,  2  ,3  ,4],
     [5,  6  ,7  ,8],
     [9, 10 ,11 ,12],]

and I want to get the 2nd row in the 3rd element (i.e. ‘7’) :

I can do it by:

A[1,2]

For the general dimension number I want to have something generic.
Given index list B=[1,2]
I want to have something like MATLAB indexing:

A[B] or A[*B]

The first gives 2 rows and the second results in an error.
How can I do this?


edit: type(A)=type(B)=np.array

Asked By: user158881

||

Answers:

You don’t need to unpack collection with "*" because numpy supports tuple indexing. You problem is that there is difference between indexing by list and by tuple. So,

import numpy as np

A = np.array([
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
])

print("indexing by list:n", A[[0, 1]], 'n')
# Output:
# indexing by list:
#   [[1 2 3 4]
#   [5 6 7 8]] 

print("indexing by tuple:n", A[(0, 1)])
# Output:
# indexing by tuple:
#   2

Hope, it helps. For the further reading about numpy indexing.

Answered By: eightlay

As an alternative, suppose you are interested in "array indexing", i.e., getting an array of values back of length L, where each value in the array is from a location in A. You would like to indicate these locations via an index of some kind.

Suppose A is N-dimensional. Array indexing solves this problem by letting you pass a tuple of N lists of length L. The ith list gives the indices corresponding to the ith dimension in A. In the simplest case, the index lists can be length-one (L=1):

>>> A[[1], [2]]
array([7])

But the index lists could be longer (L=5):

>>> A[[1,1,1,1,0], [2,2,2,2,0]]
array([7, 7, 7, 7, 1])

I emphasize that this is a tuple of lists; you can also go:

>>> first_axis, second_axis = [1,1,1,1,0], [2,2,2,2,0]
>>> A[(first_axis,second_axis)]
array([7, 7, 7, 7, 1])

You can also pass a non-tuple sequence (a list of lists rather than a tuple of lists) A[[first_axis,second_axis]] but in NumPy version 1.21.2, a FutureWarning is given noting that this is deprecated.

Another example here: https://stackoverflow.com/a/23435869/4901005

Answered By: shaneb
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.