Assign into a grid of a NumPy array given row and

2020-04-28 19:26发布

问题:

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?

回答1:

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]])


回答2:

This works too:

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