Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在numpy数组中查找与给定值最接近的值的索引。仅限于外部索引_Python_Numpy - Fatal编程技术网

Python 在numpy数组中查找与给定值最接近的值的索引。仅限于外部索引

Python 在numpy数组中查找与给定值最接近的值的索引。仅限于外部索引,python,numpy,Python,Numpy,我有一个称为方向的数组,如下所示: [[ 315. 326.31 341.57 0. 18.43 33.69 45. ] [ 303.69 315. 333.43 0. 26.57 45. 56.31] [ 288.43 296.57 315. 0. 45. 63.43 71.57] [ 270. 270. 270. 0. 90. 90. 90. ]

我有一个称为方向的数组,如下所示:

[[ 315.    326.31  341.57    0.     18.43   33.69   45.  ]
[ 303.69  315.    333.43    0.     26.57   45.     56.31]
[ 288.43  296.57  315.      0.     45.     63.43   71.57]
[ 270.    270.    270.      0.     90.     90.     90.  ]
[ 251.57  243.43  225.    180.    135.    116.57  108.43]
[ 236.31  225.    206.57  180.    153.43  135.    123.69]
[ 225.    213.69  198.43  180.    161.57  146.31  135.  ]]
我想搜索数组并找到与给定值(例如45)最近的值的索引。这就是我目前所做的:

x = np.abs(directions-45)
idx = np.where(x == x.min())
这是可行的,因为它返回所有符合此条件的索引。但是,我想将返回的索引限制为仅位于数组外部边缘的索引,即顶部行和底部行以及最右侧列和最左侧列。如果一个数字更接近不在外边缘的给定值,那么我想扩展搜索,直到在外边缘找到最近的数字

谢谢

您可以添加该行

x[1:-1, 1:-1] = x.max()+1
在查找
idx
之前,请使用高于任何边值的值覆盖中心的值

x = np.abs(directions-45)
x[1:-1, 1:-1] = x.max()+1
idx = np.where(x == x.min())
idx
Out[25]: (array([0], dtype=int64), array([6], dtype=int64))

我们可以假设一个方形数组吗?
“如果一个数字更接近给定值,而该值不在外边缘”
-closer是一个相对术语,对其接近度没有任何公差,您怎么知道?例如,假设
directions[0,-1]
90
,即不是
45
,那么我们如何判断是否在外缘找到了匹配项?