I’m new to Python from Matlab.
I want to create a new variable from a subset of an existing numpy array based on equality to some condition specified by a third numpy array, an ID in this case.
This works fine for one equality.
JavaScript
x
2
1
new_x = old_x[someID == 1]
2
But if I try to extend it several equalities at once it no longer works:
JavaScript
1
2
1
new_x = old_x[someID == 1:3]
2
Ideally I want to be able to choose many equalities, like:
JavaScript
1
2
1
new_x = old_x[someID == 1:3,7]
2
I could loop through each number I want to check but is there a simpler way of doing this?
Advertisement
Answer
You could use np.isin
+ np.r_
:
JavaScript
1
13
13
1
import numpy as np
2
3
# for reproducible results
4
np.random.seed(42)
5
6
# toy data
7
old_x = np.random.randint(10, size=100)
8
9
# create new array by filtering on boolean mask
10
new_x = old_x[np.isin(old_x, np.r_[1:3,7])]
11
12
print(new_x)
13
Output
JavaScript
1
2
1
[7 2 7 7 7 2 1 7 1 2 2 2 1 1 1 7 2 1 7 1 1 1 7 7 1 7 7 7 7 2 7 2 2 7]
2
You could substitute np.r_
by something like [1, 2, 7]
and use it as below:
JavaScript
1
2
1
new_x = old_x[np.isin(old_x, [1, 2, 7])]
2
Additionally if the array is 1-dimensional you could use np.in1d
:
JavaScript
1
3
1
new_x = old_x[np.in1d(old_x, [1, 2, 7])]
2
print(new_x)
3
Output (from in1d)
JavaScript
1
2
1
[7 2 7 7 7 2 1 7 1 2 2 2 1 1 1 7 2 1 7 1 1 1 7 7 1 7 7 7 7 2 7 2 2 7]
2