用于过滤最近距离对的Python代码

如何解决用于过滤最近距离对的Python代码

这是我的代码。请注意,这只是一个玩具数据集,我的真实集合每个表中包含大约1000个条目。

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

locations_stores = pd.DataFrame({
    'city_A' :     ['City1','City2','City3','City4',],'latitude_A':  [ 56.361176,56.34061,56.374749,56.356624],'longitude_A': [ 4.899779,4.871195,4.893847,4.912281]
})
locations_neigh = pd.DataFrame({
    'neigh_B':      ['Neigh1','Neigh2','Neigh3','Neigh4','Neigh5'],'latitude_B' : [ 53.314,53.318,53.381,53.338,53.7364],'longitude_B': [ 4.955,4.975,4.855,4.873,4.425]
})

/some calc code here/

##df_dist_long.loc[df_dist_long.sort_values('Dist(km)').groupby('neigh_B')['city_A'].min()]##


df_dist_long.to_csv('dist.csv',float_format='%.2f')

当我添加df_dist_long.loc[df_dist_long.sort_values('Dist(km)').groupby('neigh_B')['city_A'].min()]时。我收到此错误

 File "C:\Python\Python38\lib\site-packages\pandas\core\groupby\groupby.py",line 656,in wrapper                                                    
    raise ValueError                                                                                                                                  
ValueError    

                                                                        
                                                           

没有它,输出就像这样……

    city_A  neigh_B Dist(km)
0   City1   Neigh1  6.45
1   City2   Neigh1  6.42
2   City3   Neigh1  7.93
3   City4   Neigh1  5.56
4   City1   Neigh2  8.25
5   City2   Neigh2  6.67
6   City3   Neigh2  8.55
7   City4   Neigh2  8.92
8   City1   Neigh3  7.01   ..... and so on

我想要的是另一个表格,该表格过滤了最接近邻居的城市。例如,对于“ Neigh1”,City4是最近的(距离最小)。所以我想要下面的表格

city_A  neigh_B Dist(km)
0   City4   Neigh1  5.56
1   City3   Neigh2  4.32
2   City1   Neigh3  7.93
3   City2   Neigh4  3.21
4   City4   Neigh5  4.56
5   City5   Neigh6  6.67
6   City3   Neigh7  6.16
 ..... and so on

城市名称是否重复并不重要,我只想将最近的一对保存到另一个csv中。专家,请问该如何实施!

解决方法

如果只想为每个街区提供最近的城市,则不想计算完整距离矩阵。

这是一个工作代码示例,尽管我得到的输出与您的不同。也许是经纬度错误。

我使用了您的数据

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

locations_stores = pd.DataFrame({
    'city_A' :     ['City1','City2','City3','City4',],'latitude_A':  [ 56.361176,56.34061,56.374749,56.356624],'longitude_A': [ 4.899779,4.871195,4.893847,4.912281]
})
locations_neigh = pd.DataFrame({
    'neigh_B':      ['Neigh1','Neigh2','Neigh3','Neigh4','Neigh5'],'latitude_B' : [ 53.314,53.318,53.381,53.338,53.7364],'longitude_B': [ 4.955,4.975,4.855,4.873,4.425]
})

创建了一个可以查询的BallTree

from sklearn.neighbors import BallTree
import numpy as np

stores_gps = locations_stores[['latitude_A','longitude_A']].values
neigh_gps = locations_neigh[['latitude_B','longitude_B']].values

tree = BallTree(stores_gps,leaf_size=15,metric='haversine')

对于每个我们要最接近(k=1)城市/商店的邻居:

distance,index = tree.query(neigh_gps,k=1)
 
earth_radius = 6371

distance_in_km = distance * earth_radius

我们可以使用以下方法创建结果的数据框

pd.DataFrame({
    'Neighborhood' : locations_neigh.neigh_B,'Closest_city' : locations_stores.city_A[ np.array(index)[:,0] ].values,'Distance_to_city' : distance_in_km[:,0]
})

这给了我

  Neighborhood Closest_city  Distance_to_city
0       Neigh1        City2      19112.334106
1       Neigh2        City2      19014.154744
2       Neigh3        City2      18851.168702
3       Neigh4        City2      19129.555188
4       Neigh5        City4      15498.181486

由于我们的输出不同,因此有一些错误需要更正。也许交换纬度/经度,我只是在这里猜测。但这是您想要的方法,尤其是对于您的数据量。


编辑:对于完整矩阵,请使用

from sklearn.neighbors import DistanceMetric

dist = DistanceMetric.get_metric('haversine')

earth_radius = 6371

haversine_distances = dist.pairwise(np.radians(stores_gps),np.radians(neigh_gps) )
haversine_distances *= earth_radius

这将提供完整的矩阵,但请注意,对于更大的数字,这将需要很长时间,并且会期望命中内存限制。

您可以使用numpy的np.argmin(haversine_distances,axis=1)从BallTree获得类似的结果。它将产生距离最近的索引,可以像在BallTree示例中那样使用它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-