2

I have an numpy matrix, for example:

a = np.array([[1, 2], [3, 4]])

Then, I want to use another numpy matrix with indexes to extend the matrix, for example:

idxes = np.array(([0, 1, 0], [1, 0, 1]]) # the indexes matrix

The operation is like:

result = a[:, idxes] # this is an wrong expression

The result I expected is:

>>result
array([[1, 2, 1],
       [4, 3, 4]])

I want to know how to do that.

2
  • The answer is a[np.arange(len(a))[:,None], idxes], I am refraining from posting an answer in case this is a dupe. Commented Apr 2, 2019 at 3:31
  • Posting an answer because I couldn't find a duplicate for this. Commented Apr 2, 2019 at 3:42

2 Answers 2

2

You'll need to specify the a range for the first (0th) axis.

a[np.arange(len(a))[:,None], idxes]

This intuitively follows the indexing operation, the first row of idxes will index into the first row of a, the second row of idxes will index the second row of a, and so on.

Additionally, the dimensions of arange array need to be expanded from 1D to 2D because idxes is also a 2D array.

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

Comments

1

A fun way diagonal + take, diagonal here make sure you always slice the row index equal to the columns index items , which will return the just like row-wise out put

np.diagonal(np.take(a, idxes,1)).T
array([[1, 2, 1],
       [4, 3, 4]])

Or

np.diagonal(a[:,idxes]).T
array([[1, 2, 1],
       [4, 3, 4]])

3 Comments

Nice answer! Keep in mind that the result of a[:,idxes] contains many rows that you won't need as well.
@coldspeed yep , I notice that ,as I mentioned a fun way :-)
In my program, the result of a[:, idxes] is a very huge matrix, and the run time is very long. So, it is not a perfect way to do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.