2

I am trying to change a block within a two-dimensional numpy array by inserting pasting another 2-dim array. The sample below gives me unexpected behavior:

import numpy as np
M=np.ones((4,4))
print(M)
S=[0,1]
print('to be set to zero: ',M[S,:][:,S])
M[S,:][:,S]=np.zeros((2,2))
print('after setting to zero: ',M)

I would expect the upper left corner of M to become zeros. However I get

[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
to be set to zero:  [[ 1.  1.]
 [ 1.  1.]]
after setting to zero:  [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

It seems that I can extract the upper left block but not write to it. I get the expected behavior if I replace the line

M[S,:][:,S]=np.zeros((2,2))

with

M[0:2,:][:,0:2]=np.zeros((2,2))

What am I doing wrong? Thank you

2
  • 1
    You're setting entries on a copy. Commented Jun 4, 2017 at 18:44
  • 1
    M[S,:] creates a copy; M[0:2,:] a view. Commented Jun 4, 2017 at 19:34

1 Answer 1

3

You can use numpy advanced indexing ix_

M[np.ix_(S,S)]=0

M
Out[622]: 
array([[ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
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.