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

How to join the indexing in np.where?

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9,10])
ind1 = np.where(a>8)
ind2 = np.where(a<3)

What I want is [1,2,9,10].

At this time, How to join the two index, ‘ind1’ and ‘ind2’?

When I face the situation like this, I just wrote the code like below,

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

ind3 = np.where( (a>8) & (a<3) )

But if I face the more complex situation, I can not use the above code.

So I want to know the method which can find the index joining ‘ind1’ and ‘ind2’ directly, not fixing inside of ‘np.where()’.

=================================

Sorry, I mistook but already there is a good answer, so I will not erase my original question.

What I mean is below,

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9,10])
ind1 = np.where(a>8)
ind2 = np.where(a>3)

What I want to expect is [9,10].
i.e. I want to intersection.

>Solution :

You can do it by using Boolean mask arrays:

ind1 = a > 8
ind2 = a < 3
ind3 = np.logical_or(ind1, ind2)
print(a[ind3])   # --> [ 1  2  9 10]

If you have more than two condition:

ind_n = np.logical_or.reduce((ind1, ind2, ind3, ...))

For using np.where, you must change your proposed code to:

ind3 = np.where((a > 8) | (a < 3))
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