Aleksejs Fomins
Aleksejs Fomins

Reputation: 908

Numpy array thresholding acceleration

I want to construct a np.array from another np.array using a conditional. For each value, if the condition is met, one operation has to be applied, otherwise another. The calculation I have written is ugly due to conversion to and back a list. Can it be improved in terms of speed, by not converting to a list?

THR = 1.0
THR_REZ = 1.0 / THR**2

def thresholded_function(x):
  if x < THR:
    return THR_REZ
  else:
    return 1.0 / x**2

rad2 = .....some_np_array.....
rez = np.array([threshold(r2) for r2 in rad2])

Upvotes: 0

Views: 167

Answers (1)

Divakar
Divakar

Reputation: 221684

Use np.where -

np.where(x < THR, THR_REZ, 1.0/x**2) # x is input array

Sample run -

In [267]: x = np.array([3,7,2,1,8])

In [268]: THR, THR_REZ = 5, 0

In [269]: np.where(x < THR, THR_REZ, 1.0/x**2)
Out[269]: array([ 0.        ,  0.02040816,  0.        ,  0.        ,  0.015625  ])

In [270]: def thresholded_function(x, THR, THR_REZ):
     ...:   if x < THR:
     ...:     return THR_REZ
     ...:   else:
     ...:     return 1.0 / x**2

In [272]: [thresholded_function(i,THR, THR_REZ) for i in x]
Out[272]: [0, 0.02040816326530612, 0, 0, 0.015625]

Upvotes: 1

Related Questions