是否有将 numpy 数组舍入到特定数组的最佳方法?

Is there an optimal way to round a numpy array to a specific array?

Expected result

我目前正在使用此代码段进行此类操作:

Limits=Dataset[0:len(Dataset)-1]+(Dataset[1:len(Dataset)]-Dataset[0:len(Dataset)-1])/2

def RoundtoList(Data):
  Data[Data<=Limits[0]]=Dataset[0]
  for r in range(len(Limits)-1):
    Data[(Limits[r]<Data) & (Data<=Limits[r+1])]=Dataset[r+1]
  Data[Limits[len(Limits)-1]<Data]=Dataset[len(Limits)]

试试这个:

input_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def round_to_closest(val, rounding_points=[2, 5, 8]):
    
    closest_point_index = np.argmin(abs(val - np.array(rounding_points)))
    
    return rounding_points[closest_point_index]

list(map(round_to_closest, input_array))

输出:

[2, 2, 2, 5, 5, 5, 8, 8, 8, 8]