1

I am trying to find a simple numpy command to take the values of an 3D matrix according to an index array for the second coordinate. This can be done as:

import numpy as np
entry = np.array([[1, 2],[3,4],[5, 6]])
entries = np.stack([entry, entry, entry, entry])
indices = np.array([2, 1, 0, 1])

r = np.array([entries[i, indices[i], :] for i in range(len(indices))])

This code produces the correct result but uses list comprehension instead of a single command.

Is there a numpy operation that does the same? I expected np.take() to work, but it does not as it produces an array of shape (4, 4, 2) instead of (4, 2)

2
  • 2
    entries[np.arange(indices.size), indices, :] Commented Nov 30, 2024 at 16:05
  • Thanks, great, that seems to work! I am actually trying to convert the calculation to tensorflow/keras where the first dimension will be the batch size. Unfortunately there this (converted to tensors) does not seem to work. Commented Nov 30, 2024 at 22:47

1 Answer 1

0

Here's another try:

import numpy as np
entries = np.random.rand(4,3,2)
indices = np.array([2, 1, 0, 1])
r = np.array([entries[i, indices[i], :] for i in range(len(indices))])
new_r = np.diagonal(np.take(entries,indices,axis=1)).T
print(np.all(r==new_r)) # should be true

Old Answer

I found the following piece of code to produce the same array as r in your example.

np.take(entry,indices,axis=0) 

It seems that stacking is not necessary with the take function.

Edit: Taking the original question and hpaulj's comment into account. This method only works if you have an N-dimensional array of values and an index array of size M x N (Where M is the number of indices you want to sample).

Sign up to request clarification or add additional context in comments.

3 Comments

It wasn't clear whether you did that stacking to do the iteration, or whether it was just a easy way of constructing a 3d array (4,3,2) (where in general each plane was different).
Thanks, but the resulting array will still be of shape (4,3,2) while the result should be of the shape (4,2). The stacking was just to create an array with those dimensions, it might be more understandable just to use entries = np.random.rand(4,3,2)
Took another attmpt at it, might be simpler to ask a question on the tensorflow usecase

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.