0

Create a sample 3D array with shape (10, 33, 66)

data_3d = np.random.random((10, 33, 66))

Create a 2D index array with shape (33, 66) representing indices for the first dimension

index_2d = np.random.randint(0, 10, size=(33, 66))

How to slice a 2D array with shape (33,66) from the 3D array based on the index array?

4
  • 1
    It's not clear which indices you're looking to get from the 3D array. How do you interpret the meaning of the values in index_2d? For example, if index_2d[1,5] = 3, which index do you want from data_3d? Is it data_3d[3, 1, 5]? Commented Feb 12, 2024 at 18:29
  • Hi Jared, your interpretation is correct. When index_2d[1,5] = 3, I am looking for the value of data_3d[3, 1, 5] Commented Feb 12, 2024 at 18:35
  • 1
    With the newish take_along_axis, res=np.take_along_axis(data_3d, index_2d[None], axis=0) Commented Feb 12, 2024 at 21:03
  • Or 'old-fashioned' indexing: res1=data_3d[index_2d, np.arange(33)[:,None], np.arange(66)] Commented Feb 12, 2024 at 21:06

1 Answer 1

0

I think what you're looking for is the np.choose function.

chosen = np.choose(index_2d, data_3d)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.