Shew
Shew

Reputation: 1596

Updating a numpy array values based on multiple conditions

I have an array P as shown below:

P
array([[ 0.49530662,  0.32619367,  0.54593724, -0.0224462 ],
       [-0.10503237,  0.48607405,  0.28572714,  0.15175049],
       [ 0.0286128 , -0.32407902, -0.56598029, -0.26743756],
       [ 0.14353725, -0.35624814,  0.25655861, -0.09241335]])

and a vector y:

y
array([0, 0, 1, 0], dtype=int16)

I want to modify another matrix Z which has the same dimension as P, such that Z_ij = y_j when Z_ij < 0.

In the above example, my Z matrix should be

Z = array([[-, -, -, 0],
       [0, -, -, -],
       [-, 0, 1, 0],
       [-, 0, -, 0]])

Where '-' indicates the original Z values. What I thought about is very straightforward implementation which basically iterates through each row of Z and comparing the column values against corresponding Y and P. Do you know any better pythonic/numpy approach?

Upvotes: 1

Views: 612

Answers (1)

Abhijeetk431
Abhijeetk431

Reputation: 846

What you need is np.where. This is how to use it:-

import numpy as np
z = np.array([[ 0.49530662,  0.32619367,  0.54593724, -0.0224462 ],
       [-0.10503237,  0.48607405,  0.28572714,  0.15175049],
       [ 0.0286128 , -0.32407902, -0.56598029, -0.26743756],
       [ 0.14353725, -0.35624814,  0.25655861, -0.09241335]])
y=([0, 0, 1, 0])
result = np.where(z<0,y,z)
#Where z<0, replace it by y

Result

>>> print(result)
[[0.49530662 0.32619367 0.54593724 0.        ]
 [0.         0.48607405 0.28572714 0.15175049]
 [0.0286128  0.         1.         0.        ]
 [0.14353725 0.         0.25655861 0.        ]]

Upvotes: 1

Related Questions