Prashanth
Prashanth

Reputation: 115

Search a Numpy Array based on array index

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

Upvotes: 0

Views: 91

Answers (1)

mathdan
mathdan

Reputation: 191

Try (for example):

condition = np.zeros_like(A, dtype='bool')
condition[0:2, 0:1] = (A[0:2, 0:1] % 2 ==0)

Upvotes: 1

Related Questions