Home > Software design >  How to join the indexing in np.where?
How to join the indexing in np.where?

Time:03-19

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,

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.

CodePudding user response:

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))

CodePudding user response:

Why not do a for loop?

idx = []
for i in range X:
  idx.append(np.where(some condition))

results = np.concat(idx)
  • Related