Numpy数组阈值加速度

时间:2017-11-08 11:49:40

标签: python arrays numpy threshold

我想使用条件从另一个np.array构造一个np.array。对于每个值,如果满足条件,则必须应用一个操作,否则应用另一个操作。我写的计算由于转换到列表而变得难看。是否可以通过不转换为列表来提高速度?

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])

1 个答案:

答案 0 :(得分:1)

使用np.where -

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

示例运行 -

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]