Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditionally replace values on three 2d numpy arrays

I have three 2×2 numpy arrays like so:

import numpy as np

#create three arrays
one = np.array([[1, -1], 
                [-1, 1]])

two = np.array([[-1, 0], 
                [-2, 2]])

three = np.array([[1, 1], 
                [-4, 3]])

I want to make a fourth 2×2 array and replace the values based on one, two and three so that if in a particular location all three arrays have values less than one, to make the new value -1, and if all three arrays have values greater than one, to make the new value 1. If the condition is not met I want to turn the values to 0.

I am attempting this like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#make a copy of one 
final = one.copy()

#where all of the three initial arrays are > 0 make the value 1
final[(one > 0) & (two > 0) & (three >0)] = 1

#where all of the three initial arrays are < 0 make the value -1
final[(one < 0) & (two < 0) & (three <0)] = -1

which returns:

array([[ 1, -1],
       [-1,  1]])

So in this case the index at [0,0] and [0,1] I want to return zero while [1,0] should be -1 and [1,1] should be 1 or this:

[0, 0,
[-1, 1]

I think it is because I am not saying how to change the value to 0 when the original two conditions are not met, and I can’t seem to work out how to do that.

>Solution :

With np.select for multiple choices on conditions (and default value 0):

final = np.select([(one > 0) & (two > 0) & (three > 0), 
                   (one < 0) & (two < 0) & (three < 0)], [1, -1])
print(final)

[[ 0  0]
 [-1  1]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading