1

I'm trying to slice an Ndarray a with a list b. But the behaviour is not as I would expect it. What do I have to change to get the wanted result?

a = np.arange(27).reshape(3,3,3)

b = [2,2]

Actual behaviour:

a[:,b]

array([[[ 6,  7,  8],
        [ 6,  7,  8]],

       [[15, 16, 17],
        [15, 16, 17]],

       [[24, 25, 26],
        [24, 25, 26]]])

Wanted behaviour:

a[:,2,2]

array([ 8, 17, 26])
michmest
  • 25
  • 4

1 Answers1

3

Try replacing : with slice(None) and unpacking b:

a[(slice(None), *b)]
# [ 8 17 26]

import numpy as np

a = np.arange(27).reshape((3, 3, 3))
b = [2, 2]
result = a[(slice(None), *b)]

print(result)
# [ 8 17 26]
print((result == a[:, 2, 2]).all())
# True
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57