每行邻居列表,作为两列X Y的基准框架中的新列



在以下数据帧中:

x,y
1,2
3,7
10,4
5,3
7,7
1,6

我正在努力寻找最快的方法来完成它。我的简单尝试是检查它们是否在一个圆圈内。

def check_neighboor(x1, y1, x2, y2 , r):
return (x1-x2)**2 + (y1-y2)**2 < r**2
dx = df.apply(check_neighboor(df['X'], df['Y'], df['X'].T, df['Y'].T, 5))

我知道我需要对整个列进行迭代。任何蟒蛇式、泛戴式和快速的方法都值得赞赏。

样本输出(不完整(:

x,y, n
1,2, [(1,6),(3,7)(5,3)]
3,7, [1,6][5,3]
10,4 []
5,3  [(5,3),(3,7),(7,7)]
7,7 ...
1,6

这将为您提供一个元组对列表,这些元组对表示相邻点的索引

x = df["x"].to_numpy()
y = df["y"].to_numpy()
r = 5
list(
pd.DataFrame(
np.add(
np.square(np.subtract.outer(x,x)),
np.square(np.subtract.outer(y,y)),
) < r**2
)
.melt(ignore_index=False)
.reset_index()
.query("value and index != variable")
.pipe(lambda d: zip(d.iloc[:,0], d.iloc[:,1]))
)

最新更新