1

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?

2
  • 3
    Won't np.where work as suggested in the linked dup of your previous question - stackoverflow.com/questions/55947579? Commented May 2, 2019 at 10:58
  • Now got it cleared. Just now realizing it works as a if else. Commented May 2, 2019 at 11:32

1 Answer 1

1

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.        ]]
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.