假设我有以下两个数组:
Suppose I have the following two arrays:
>>> a = np.random.normal(size=(5,)) >>> a array([ 1.42185826, 1.85726088, -0.18968258, 0.55150255, -1.04356681]) >>> b = np.random.normal(size=(10,10)) >>> b array([[ 0.64207828, -1.08930317, 0.22795289, 0.13990505, -0.9936441 , 1.07150754, 0.1701072 , 0.83970818, -0.63938211, -0.76914925], [ 0.07776129, -0.37606964, -0.54082077, 0.33910246, 0.79950839, 0.33353221, 0.00967273, 0.62224009, -0.2007335 , -0.3458876 ], [ 2.08751603, -0.52128218, 1.54390634, 0.96715102, 0.799938 , 0.03702108, 0.36095493, -0.13004965, -1.12163463, 0.32031951], [-2.34856521, 0.11583369, -0.0056261 , 0.80155082, 0.33421475, -1.23644508, -1.49667424, -1.01799365, -0.58232326, 0.404464 ], [-0.6289335 , 0.63654201, -1.28064055, -1.01977467, 0.86871352, 0.84909353, 0.33036771, 0.2604609 , -0.21102014, 0.78748329], [ 1.44763687, 0.84205291, 0.76841512, 1.05214051, 2.11847126, -0.7389102 , 0.74964783, -1.78074088, -0.57582084, -0.67956203], [-1.00599479, -0.93125754, 1.43709533, 1.39308038, 1.62793589, -0.2744919 , -0.52720952, -0.40644809, 0.14809867, -1.49267633], [-1.8240385 , -0.5416585 , 1.10750423, 0.56598464, 0.73927224, -0.54362927, 0.84243497, -0.56753587, 0.70591902, -0.26271302], [-1.19179547, -1.38993415, -1.99469983, -1.09749452, 1.28697997, -0.74650318, 1.76384156, 0.33938808, 0.61647274, -0.42166111], [-0.14147554, -0.96192206, 0.14434349, 1.28437894, -0.38865447, -1.42540195, 0.93105528, 0.28993325, -1.16119916, -0.58244758]])我必须找到一种方法将所有值从b舍入到a中最接近的值.
I have to find a way to round all values from b to the nearest value found in a.
有人知道用python做到这一点的好方法吗?我自己一无所获.
Does anyone know of a good way to do this with python? I am at a total loss myself.
推荐答案您可以尝试以下方法
import numpy as np def rounder(values): def f(x): idx = np.argmin(np.abs(values - x)) return values[idx] return np.frompyfunc(f, 1, 1) a = np.random.normal(size=(5,)) b = np.random.normal(size=(10,10)) rounded = rounder(a)(b) print(rounded)rounder函数采用我们要四舍五入的值.它创建一个函数,该函数采用标量并返回values数组中最接近的元素.然后,我们使用 numpy.frompyfunc .这样,您不仅可以在2d数组上使用它,numpy会自动为您进行广播,而不会产生任何循环.
The rounder function takes the values which we want to round to. It creates a function which takes a scalar and returns the closest element from the values array. We then transform this function to a broadcast-able function using numpy.frompyfunc. This way you are not limited to using this on 2d arrays, numpy automatically does broadcasting for you without any loops.
更多推荐
将值列表四舍五入到python中另一个列表的最接近值
发布评论