'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,
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 1:[1]
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))
Solution 2:[2]
Why not do a for loop?
idx = []
for i in range X:
idx.append(np.where(some condition))
results = np.concat(idx)
Solution 3:[3]
In [41]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
...: ind1 = np.where(a > 8)
...: ind2 = np.where(a > 3)
...:
First, make sure you understand what each where/nonzero produces:
In [42]: ind1, ind2
Out[42]: ((array([8, 9]),), (array([3, 4, 5, 6, 7, 8, 9]),))
That's a tuple with one array (since a is 1d).
We can extract that array:
In [43]: ind1[0], ind2[0]
Out[43]: (array([8, 9]), array([3, 4, 5, 6, 7, 8, 9]))
numpy set operations aren't that great. But we can use Python sets:
In [45]: set(ind1[0]), set(ind2[0])
Out[45]: ({8, 9}, {3, 4, 5, 6, 7, 8, 9})
In [46]: set(ind1[0]).intersection(set(ind2[0]))
Out[46]: {8, 9}
Doing logical operations on the boolean inputs to where is usually a better choice.
We could test the 2 arrays for equality:
In [50]: ind1[0][:, None] == ind2[0]
Out[50]:
array([[False, False, False, False, False, True, False],
[False, False, False, False, False, False, True]])
In [52]: (ind1[0][:, None] == ind2[0]).any(axis=0)
Out[52]: array([False, False, False, False, False, True, True])
In [53]: ind2[0][(ind1[0][:, None] == ind2[0]).any(axis=0)]
Out[53]: array([8, 9])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Charbel-Raphaël Segerie |
| Solution 3 |
