Reputation: 133
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
Upvotes: 1
Views: 469
Reputation: 1474
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 i
th list gives the indices corresponding to the i
th 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
Upvotes: 1
Reputation: 542
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.
Upvotes: 2