0

I have a 2D numpy array and I would like to change some of the elements based on two criteria: The first criteria is a condition. The second criteria is based on the index of the array (row and column number)

For instance take the following code,

import numpy as np
#Create an 8x8 array
A = np.arange(64).reshape(8,8)
condition = (A %2 ==0)
B = np.where(condition,0,A)
print B

This works but I don't want to apply the condition on the entire domain of A. I only want to apply the condition on a user-specified range of cells, say the first three rows and first two columns.

How can I modify my code to accomplish this ?

Thanks! PK

Edit : Updated code based on MathDan's suggestion

import numpy as np

#Create an 8x8 array
A = np.arange(64).reshape(8,8)
#Create boolean conditional array
condition = np.zeros_like(A,dtype='bool')
#Enforce condition on the first 4X4 matrix
condition[0:4, 0:4] = (A[0:4, 0:4] % 2 ==0)
B = np.where(condition,0,A)
print B
1
  • Thanks Mathdan. That seems so easy and intuitive that I am kicking myself for not thinking of it. condition = zeros_like(A,dtype='bool') condition[0:2][0:1] = (A[0:2][0:1] % 2 ==0) B = np.where(condition,0,A) Commented Jun 27, 2014 at 17:18

1 Answer 1

1

Try (for example):

condition = np.zeros_like(A, dtype='bool')
condition[0:2, 0:1] = (A[0:2, 0:1] % 2 ==0)
Sign up to request clarification or add additional context in comments.

4 Comments

I tried that but it didn't work for me. Maybe I am missing something. condition[0:2][0:1] = (A[0:2][0:1] % 2 ==0) followed by C = np.where(condition,0,A) give me : shape mismatch error
Right, sorry. I left out a line: condition = zeros_like(A,dtype='bool')
A[0:2][0:1] is not the same as A[0:2, 0:1], you want the second one. The fist one will index in the first dimension twice.
Thanks for the correction, Bi Rico. I incorporated it into the answer.

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.