1

I want to access a specific row and column restriction of a 2d numpy array.

> x
array([[1, 2, 0],
       [3, 4, 0],
       [0, 0, 1]])

If I do what seems natural, I just get the diagonal elements of the restricted array.

> x[[0,1], [0,1]]
array([1, 4])

Instead I can do this to read what I want -

> x[[0,1],:][:,[0,1]]
array([[1, 2],
       [3, 4]])

..but it doesn't let me write/assign the values.

> x[[0,1],:][:,[0,1]] = np.array([[1,0],[0,1]])

> x 
array([[1, 2, 0],
       [3, 4, 0],
       [0, 0, 1]])

How can I write to a matrix here?

2 Answers 2

2

Use np.ix_ to map that grid of elements and then assign -

x[np.ix_([0,1], [0,1])] = np.array([[1,0],[0,1]])
Sign up to request clarification or add additional context in comments.

Comments

0

This works too:

x[:2, :2] = np.array([[1, 0], [0, 1]])

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.