cagri
cagri

Reputation: 71

Modifying entire row of an array based on a condition using Numpy

I have an array:

xNew = np.array([[0.50,0.25],[-0.4,-0.2],[0.60,0.80],[1.20,1.90],[-0.10,0.60],[0.10,1.2]])

and another array:

x = np.array([[0.55,0.34],[0.45,0.26],[0.14,0.29],[0.85,0.89],[0.27,0.78],[0.45,0.05]])

If an element in a row is smaller than 0 or larger than 1 in xNew , that row should be entirely replaced by corresponding row in x. The desired output is:

xNew = np.array([[0.50,0.25],[0.45,0.26],[0.60,0.80],[0.85,0.89],[0.27,0.78],[0.45,0.05]])

I am looking for an efficient way to accomplish this using numpy functions.

Thanks!

Upvotes: 1

Views: 53

Answers (2)

Ani
Ani

Reputation: 539

for index, y in enumerate(xNew):
    if(np.any(np.greater(y,[1,1])) or np.any(np.less(y,[0,0]))):
        xNew[index] = x[index]

Upvotes: 0

Ehsan
Ehsan

Reputation: 12407

You can use advanced indexing:

idx = ((xNew<0)|(xNew>1)).any(-1)
xNew[idx]=x[idx]

output:

[[0.5  0.25]
 [0.45 0.26]
 [0.6  0.8 ]
 [0.85 0.89]
 [0.27 0.78]
 [0.45 0.05]]

Upvotes: 1

Related Questions