首先,让我们试试到create a Minimal, Complete, and Verifiable example
>>> import pandas as pd
>>> import numpy as np
>>> x0, dx = 0, 0.959131
>>> x = np.arange(x0, x0+5*dx,dx)
>>> y0, dy = -9.4901299629261011, 8.980481-8.470837
>>> y = np.arange(y0, y0+2*dy,dy)
>>> data = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
>>> grid = pd.DataFrame(data=data, columns=['x', 'y'])
>>> grid.head()
x y
0 0.000000 -9.49013
1 0.959131 -9.49013
2 1.918262 -9.49013
3 2.877393 -9.49013
4 3.836524 -9.49013
其中grid.head() 是基于grid 的图形表示的数字等价物
>>> grid
x y
0 0.000000 -9.490130 # the red dot
1 0.959131 -9.490130 # the bottom right blue square
2 1.918262 -9.490130
3 2.877393 -9.490130
4 3.836524 -9.490130
5 0.000000 -8.980486 # the middle left blue square
6 0.959131 -8.980486 # the green diamond
7 1.918262 -8.980486
8 2.877393 -8.980486
9 3.836524 -8.980486
10 0.000000 -8.470842 # the unwanted top left blue square
11 0.959131 -8.470842
12 1.918262 -8.470842
13 2.877393 -8.470842
14 3.836524 -8.470842
因此,您希望点 1、5 和 6 作为点 0 的邻域。
为此,您可能需要查看the sklearn.neighbors module which implements the k-nearest neighbors algorithm 的函数kneighbors_graph。玩弄它,并设置Minkowski metric、p的幂参数,大于2,比如说3(取p>2的想法基本上是为了减少欧几里得平方根2因子- - 在单位正方形的对角线和边之间--朝向1),如下
>>> from sklearn.neighbors import kneighbors_graph
>>> _3n_graph = kneighbors_graph(grid,
n_neighbors=3,
p=3,
mode='connectivity',
include_self=False)
产量
>>> grid.iloc[_3n_graph[0].indices]
x y
5 0.000000 -8.980486
1 0.959131 -9.490130
6 0.959131 -8.980486