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

Compare Elements in One Array with Two Other Arrays by Position in Numpy

I have a numpy array (a_array) and I need to compare each element with the elements in the same position in b_array and c_array, returning the lower of those two values.

a_array = [5031 5038 5040]
b_array = [5050 5055 5870]
c_array = [5611 5743 5780]

So in the above example:

i. compare 5031 with 5050 and 5611 returning 5050;

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

ii. compare 5038 with 5055 and 5743 returning 5055;

iii. compare 5040 with 5870 and 5780 returning 5780.

I could use a for loop to do this but is there a vecotorized approach?

>Solution :

If you only care about b_array/c_array, use numpy.minimum:

np.minimum(b_array, c_array)

Output: array([5050, 5055, 5780])

If you want to consider all arrays, you can use np.minimum.reduce:

np.minimum.reduce([a_array, b_array, c_array])

Or hstack and min:

np.vstack([a_array, b_array, c_array]).min(axis=0)

Output: array([5031, 5038, 5040])

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