1

I have a multidimensional Numpy array; let's say it's

 myArray = array([[[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8]],

                  [[ 9, 10, 11],
                   [12, 13, 14],
                   [15, 16, 17]],

                  [[18, 19, 20],
                   [21, 22, 23],
                   [24, 25, 26]]])

I know that running myArray[1,1,1], for instance, will return 13. However, I want to define indx = [1,1,1] then call something to the effect ofmyArray[indx]. However, this does some other multidimensional indexing stuff.

I have also tried myArray[*indx] but that understandably throws a syntax error.

Currently my very ugly workaround is to define

def array_as_indices(array, matrix):
    st = ''
    for i in array:
        st += '%s,' % i
    st = st[:-1]

    return matrix[eval(st)]

which works but is quite inelegant and presumably slow.

Is there a more pythonic way to do what I'm looking for?

1
  • use myArray[tuple(indx)] Commented Jun 2, 2020 at 19:31

2 Answers 2

2

This is a duplicate of Unpacking tuples/arrays/lists as indices for Numpy Arrays, but you can just create a tuple

import numpy as np


def main():
    my_array = np.array(
        [
            [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
            [[9, 10, 11], [12, 13, 14], [15, 16, 17]],
            [[18, 19, 20], [21, 22, 23], [24, 25, 26]],
        ]
    )
    print(f"my_array[1,1,1]: {my_array[1,1,1]}")
    indx = (1, 1, 1)
    print(f"my_array[indx]: {my_array[indx]}")


if __name__ == "__main__":
    main()

will give

my_array[1,1,1]: 13
my_array[indx]: 13
Sign up to request clarification or add additional context in comments.

Comments

1

The indices of a numpy array are addressed by tuples, not lists. Use indx = (1, 1, 1).

As an extension, if you want to call the indices (1, 1, 1) and (2, 2, 2), you can use

>>> indx = ([1, 2], [1, 2], [1, 2])
>>> x[indx]
array([13, 26])

The rationale behind the behavior with lists is that numpy treats lists sequentially, so

>>> indx = [1, 1, 1]
>>> x[indx]
array([[[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]]])

It returns a list of three elements, each equal to x[1].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.