1

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

user158881
  • 133
  • 8
  • 1
    Do we talk about standard Python 3 lists? Because both A[1, 2] and A[[1, 2]] is illegal and will cause `TypeError: list indices must be integers or slices, not tuple` error. Or is it, for example, numpy's array? – eightlay Oct 13 '22 at 15:09
  • np.array. thanks for the note. i'll clarify in the question – user158881 Oct 13 '22 at 15:13
  • I found this (ugly) solution: B = tuple( np.reshape(B,(1, len(B)))) and than: A(B) hoping for better one – user158881 Oct 13 '22 at 15:30

2 Answers2

2

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.

eightlay
  • 423
  • 2
  • 9
1

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

shaneb
  • 1,314
  • 1
  • 13
  • 18
  • thanks for the extention for several outputs. the question still stands. will you be able to index it like: A[(first_axis,second_axis)] and first_axis, second_axis = [1,1,1,1,0], [2,2,2,2,0] – user158881 Oct 18 '22 at 10:14
  • 1
    Yes, I clarified that a tuple of lists is needed, and you can use list variables in your tuple. – shaneb Oct 18 '22 at 16:50