2

Assumes there is an index and a matrix L

>>> index
(array([0, 2, 3, 3]), array([0, 2, 2, 3]))
>>> L
array([[  1,  -1,  -5, -10],
   [-15,   0,  -1,  -5],
   [-10, -15,  10,  -1],
   [ -5, -10,   1,  15]])

I want to select the columns according to the index[1], I've tried:

>>> L[:,index[1]]
array([[  1,  -5,  -5, -10],
   [-15,  -1,  -1,  -5],
   [-10,  10,  10,  -1],
   [ -5,   1,   1,  15]])

but the result is not i expected, what I expected is:

>>> for i in index[1]:
...     print L[:,i]
[  1 -15 -10  -5]
[-5 -1 10  1]
[-5 -1 10  1]
[-10  -5  -1  15]

How can i get the expected result without for loop? and why this unexpected result comes out? Thanks.

1 Answer 1

3

You simply need to transpose it:

L[:,index[1]].T
#             ^ transpose

By using a transpose, the columns are rows and vice versa. So here (you can transpose before the selection, and then use L.T[index[1],:]) we first make the selection and then turn the columns into rows.

This produces:

>>> L[:,index[1]].T
array([[  1, -15, -10,  -5],
       [ -5,  -1,  10,   1],
       [ -5,  -1,  10,   1],
       [-10,  -5,  -1,  15]])

Note that of course behind the curtains there are still some loops that are done. But these are done outside Python and thus are more efficient.

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

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.