如何使用向量化从最接近数组中值的数组中选择值? [英] How to select value from array that is closest to value in array using vectorization?

查看:99
本文介绍了如何使用向量化从最接近数组中值的数组中选择值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要根据线性选择最接近的选择从一个选择数组中替换一个值数组.

I have an array of values that I want to replace with from an array of choices based on which choice is linearly closest.

捕获的是在运行时定义的选择大小.

The catch is the size of the choices is defined at runtime.

import numpy as np
a = np.array([[0, 0, 0], [4, 4, 4], [9, 9, 9]])
choices = np.array([1, 5, 10])

如果选择的大小是静态的,我将简单地使用np.where

If choices was static in size, I would simply use np.where

d = np.where(np.abs(a - choices[0]) > np.abs(a - choices[1]), 
      np.where(np.abs(a - choices[0]) > np.abs(a - choices[2]), choices[0], choices[2]),
         np.where(np.abs(a - choices[1]) > np.abs(a - choices[2]), choices[1], choices[2]))

要获取输出:

>>d
>>[[1, 1, 1], [5, 5, 5], [10, 10, 10]]

有没有办法在保持向量化的同时更动态地执行此操作.

Is there a way to do this more dynamically while still preserving the vectorization.

推荐答案

a减去选择,找到结果最小值的索引,替换.

Subtract choices from a, find the index of the minimum of the result, substitute.

a = np.array([[0, 0, 0], [4, 4, 4], [9, 9, 9]])
choices = np.array([1, 5, 10])
b = a[:,:,None] - choices
np.absolute(b,b)
i = np.argmin(b, axis = -1)
a = choices[i]
print a

>>> 
[[ 1  1  1]
 [ 5  5  5]
 [10 10 10]]

a = np.array([[0, 3, 0], [4, 8, 4], [9, 1, 9]])
choices = np.array([1, 5, 10])
b = a[:,:,None] - choices
np.absolute(b,b)
i = np.argmin(b, axis = -1)
a = choices[i]
print a

>>>    
[[ 1  1  1]
 [ 5 10  5]
 [10  1 10]]
>>> 


将额外的维添加到了a,以便从a的每个元素中减去choices的每个元素. choices在第三次针对a进行了广播维度,此链接具有不错的图形. b.shape是(3,3,3). EricsBroadcastingDoc 是一个很好的解释,并且在结束.


The extra dimension was added to a so that each element of choices would be subtracted from each element of a. choices was broadcast against a in the third dimension, This link has a decent graphic. b.shape is (3,3,3). EricsBroadcastingDoc is a pretty good explanation and has a graphic 3-d example at the end.

对于第二个示例:

>>> print b
[[[ 1  5 10]
  [ 2  2  7]
  [ 1  5 10]]

 [[ 3  1  6]
  [ 7  3  2]
  [ 3  1  6]]

 [[ 8  4  1]
  [ 0  4  9]
  [ 8  4  1]]]
>>> print i
[[0 0 0]
 [1 2 1]
 [2 0 2]]
>>> 

最终分配使用索引数组整数数组索引.

在第二个示例中,请注意元素a[0,1]有一个 tie ,其中一个或五个都可以被替换.

In the second example, notice that there was a tie for element a[0,1] , either one or five could have been substituted.

这篇关于如何使用向量化从最接近数组中值的数组中选择值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆