I have a 3D numpy array data
and another array pos
of indexes (an index is a numpy array on its own, which makes the latter array a 2D array):
import numpy as np
data = np.arange(8).reshape(2, 2, -1)
#array([[[0, 1],
# [2, 3]],
#
# [[4, 5],
# [6, 7]]])
pos = np.array([[1, 1, 0], [0, 1, 0], [1, 0, 0]])
#array([[1, 1, 0],
# [0, 1, 0],
# [1, 0, 0]])
I want to select and/or mutate the elements from data
using the indexes from pos
. I can do the selection using a for
loop or a list comprehension:
[data[tuple(i)] for i in pos]
#[6, 2, 4]
data[[i for i in pos.T]]
#array([6, 2, 4])
But this does not seem to be a numpy way. Is there a vectorized numpy solution to this problem?