1

Let's say I have this numpy matrix:

>>> mat = np.matrix([[3,4,5,2,1], [1,2,7,6,5], [8,9,4,5,2]])
>>> mat
matrix([[3, 4, 5, 2, 1],
        [1, 2, 7, 6, 5],
        [8, 9, 4, 5, 2]])

Now let's say I have some indexes in this form:

>>> ind = np.matrix([[0,2,3], [0,4,2], [3,1,2]])
>>> ind
matrix([[0, 2, 3],
        [0, 4, 2],
        [3, 1, 2]])

What I would like to do is to get three values from each row of the matrix, specifically values at columns 0, 2, and 3 for the first row, values at columns 0, 4 and 2 for the second row, etc. This is the expected output:

matrix([[3, 5, 2],
        [1, 5, 7],
        [5, 9, 4]])

I've tried using np.take but it doesn't seem to work. Any suggestion?

2 Answers 2

3

This is take_along_axis.

>>> np.take_along_axis(mat, ind, axis=1)
matrix([[3, 5, 2],
        [1, 5, 7],
        [5, 9, 4]])
Sign up to request clarification or add additional context in comments.

Comments

2

This will do it: mat[np.arange(3).reshape(-1, 1), ind]

In [245]: mat[np.arange(3).reshape(-1, 1), ind]
Out[245]: 
matrix([[3, 5, 2],
        [1, 5, 7],
        [5, 9, 4]])

(but take_along_axis in @user3483203's answer is simpler).

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.