I’m trying to solve whether or not each element in a 3d numpy array fits within a certain threshold. Currently I have nested for loops that get the job done, but it’s really slow and I don’t have all day to wait for my code to run LOL. The input spec is a little bit weird so I haven’t been able to find any more efficient solutions. Here’s an example:
input matrix:
JavaScript
x
15
15
1
[
2
[
3
[4, 5, 2],
4
[5, 6, 4]
5
],
6
[
7
[4, 4, 2],
8
[5, 8, 0]
9
],
10
[
11
[8, 4, 6],
12
[0, 6, 8]
13
]
14
]
15
upper threshold: 5
lower threshold:
JavaScript
1
5
1
[
2
[1, 0, 4],
3
[1, 2, 2]
4
]
5
and the output should be:
JavaScript
1
15
15
1
[
2
[
3
[1, 0, 1],
4
[1, 0, 1]
5
],
6
[
7
[1, 1, 0],
8
[1, 0, 0]
9
],
10
[
11
[0, 1, 0],
12
[0, 0, 0]
13
]
14
]
15
Advertisement
Answer
Broadcasting saves the day!
JavaScript
1
26
26
1
x = np.array([
2
[
3
[4, 5, 2],
4
[5, 6, 4],
5
],
6
[
7
[4, 4, 2],
8
[5, 8, 0],
9
],
10
[
11
[8, 4, 6],
12
[0, 6, 8],
13
],
14
])
15
16
upper_thresh = 5
17
18
lower_thresh = np.array([
19
[1, 0, 4],
20
[1, 2, 2],
21
])
22
23
within_lower = x > lower_thresh
24
within_upper = x < upper_thresh
25
within_bound = (within_lower & within_upper).astype(dtype=np.int64)
26
And now:
JavaScript
1
10
10
1
>>> print(within_bound)
2
[[[1 0 0]
3
[0 0 1]]
4
5
[[1 1 0]
6
[0 0 0]]
7
8
[[0 1 0]
9
[0 0 0]]]
10
(Not sure if you wanted inclusive thresholds. In that case, use <=
and >=
for comparisons instead.)