I have an array like this:
a = np.array([
[0.02, 1.01, 4.01, 3.00, 5.12],
[2.11, 1.50, 3.98, 0.52, 5.01]])
and a "condition" array:
c = np.array([0, 1, 4, 5])
I want to round a[i][j]=c[k]
if c[k] - const < a[i][j] < c[k] + const
, otherwise a[i][j] = 0
For example, if const = 0.05
. The result could be:
a_result = [[0 1 4 0 0]
[0 0 4 0 5]]
The navie way is to use 3 for loop to check for each a[i][j]
and c[k]
. However, it's very slow when a
is big. Do we have a fast "python way" to do this?
For loop (slow) solution:
a_result = np.full(a.shape, 0)
const = 0.05
mh, mw = a.shape
for i in range(mh-1):
for j in range(mw-1):
for k in range(1, len(c)):
if a[i][j] > (c[k] - const) and a[i][j] < (c[k] + const):
a_result[i][j] = c[k]