You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于X/Y坐标计算指定半径内点数量的Python代码问题排查

解决DataFrame坐标点指定半径内邻点统计问题

我编写了一段Python代码,想要统计DataFrame中每个X/Y坐标点作为圆心时,指定半径圆内的其他点数量。参考经纬度问题的解法用了Scikit-Learn的BallTree,但输出不符合预期——比如输入radius=100时,结果是[1 1 1 1 1],显然不对。原代码如下:

原代码:

import numpy as np
import pandas as pd
from sklearn.neighbors import BallTree

df = pd.DataFrame({'id':list('abcde'),'X': [10, 1000, 1010, 5000, 5100],'Y': [10, 1000, 1010, 5000, 5100]})

radius = int(input('Enter the selection radius of the circle:'))

coords = df[["X","Y"]]

tree = BallTree(coords, metric='haversine')
answers = tree.query_radius(coords, r=radius, count_only=True)

print(answers)

错误原因

  • 核心问题是误用了haversine度量:这个度量专门用于经纬度坐标(需转换为弧度),计算的是球面距离,而你的数据是平面直角坐标,单位和度量逻辑完全不匹配,导致输入的radius值在球面距离计算下极小,每个点只能匹配到自己。
  • query_radius默认会把点自身计入统计,所以结果全为1。

修正方案

只需两步即可解决:

  1. 将BallTree的度量改为**euclidean**(欧几里得距离,适用于平面直角坐标);
  2. 统计结果减1,排除点自身。

修正后的代码:

import numpy as np
import pandas as pd
from sklearn.neighbors import BallTree

df = pd.DataFrame({'id':list('abcde'),'X': [10, 1000, 1010, 5000, 5100],'Y': [10, 1000, 1010, 5000, 5100]})

radius = int(input('Enter the selection radius of the circle:'))

coords = df[["X","Y"]]

# 更换为欧几里得距离度量
tree = BallTree(coords, metric='euclidean')
# 统计时排除自身,结果减1
answers = tree.query_radius(coords, r=radius, count_only=True) - 1

print(answers)

验证结果

输入radius=100时,输出为[0 1 1 0 1],符合预期:

  • 点(10,10)周围无其他点;
  • 点(1000,1000)和(1010,1010)互相在对方半径范围内;
  • 点(5000,5000)周围有1个点,点(5100,5100)周围有1个点。

内容的提问来源于stack exchange,提问作者ConorC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:58:21