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

如何将BallTree输出的距离、索引numpy数组映射到pandas DataFrame

具体操作步骤

你拿到的indices数组里的每个值,就是构建BallTree的locations_a数据集对应的行索引,直接按索引映射取值再合并即可,完整操作如下:

1. 把查询结果并入查询数据集

ball.query()返回的两个数组都是二维结构(维度为[查询样本数, k]),先拍平为一维后加入locations_b:

# 拍平二维数组,并入查询数据集
locations_b['nearest_distance_km'] = distances.flatten()
locations_b['loc_a_matched_index'] = indices.flatten()

2. 映射关联locations_a的最近邻信息

用匹配到的索引从locations_a取出对应的站点、经纬度信息,合并到结果中:

# 关联locations_a中对应索引的信息
locations_b['nearest_station'] = locations_a.loc[locations_b['loc_a_matched_index'], 'STATION NAME'].values
locations_b['nearest_lat'] = locations_a.loc[locations_b['loc_a_matched_index'], 'LAT'].values
locations_b['nearest_lon'] = locations_a.loc[locations_b['loc_a_matched_index'], 'LON'].values

# 可选:删除不需要的中间索引列
locations_b.drop('loc_a_matched_index', axis=1, inplace=True)

3. 直观查看结果

筛选需要的字段打印即可看到每个查询点对应的最近邻明细:

# 输出核心信息列
print(locations_b[['STATION NAME', 'LAT', 'LON', 'nearest_station', 'nearest_lat', 'nearest_lon', 'nearest_distance_km']])

运行后你就能看到locations_b里每个站点,对应在locations_a里的最近邻站点名称、经纬度、距离的完整信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:09:00