将值列表四舍五入到python中另一个列表的最接近值

编程入门 行业动态 更新时间:2024-10-13 12:24:53
本文介绍了将值列表四舍五入到python中另一个列表的最接近值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下两个数组:

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中另一个列表的最接近值

本文发布于:2023-11-07 23:28:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   最接近   四舍五入   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!