【问题标题】:Trying to find all coordinate points within a certain range试图找到一定范围内的所有坐标点
【发布时间】:2022-06-11 20:48:02
【问题描述】:

我在这里想要实现的是,我有一个 源 csv 文件,其中填充了坐标和一个额外的 目标 csv 文件,其中包含我想要的更多坐标从源csv文件中的每个坐标中找出目标csv文件中所有坐标在一定范围内。

坐标格式为xx.xxxxxxyy.yyyyyy

“lat1”和“long1”是源csv中坐标列的名称,“lat2”和“long2”是目标csv中的坐标列。

import pandas as pd
import numpy as np
import time 
from playsound import playsound

fast_df = pd.read_csv('target.csv') # 2
el_df = pd.read_csv('source.csv') # 1

"""
Commandos:
    
    coords_file.columns - get columns
    coords_file.drop_duplicates() - removes identical rows
    coords_flie.iloc[] - fetch row with index
    coords_file[['OBJEKT_ID', 'EXTERNID', 'DETALJTYP']]
    
"""


def findDistance(row, source_lat, source_long):
    # print(row, source_lat, source_long)
    row_lat = row['lat2']
    row_long = row['long2']
    lat_diff = np.abs(source_lat - row_lat)/0.00001 # divide by 0.00001 to convert to meter
    long_diff = np.abs(source_long - row_long)/0.00001
    row['Distance'] = np.sqrt(lat_diff**2+long_diff**2)
    return row

def findDistance_(source_coordinates, target_coordinates):
    lat_diff = np.abs(source_coordinates[0] - target_coordinates[0])/0.00001 # divide by 0.00001 to convert to meter
    long_diff = np.abs(source_coordinates[1] - target_coordinates[1])/0.00001
    Distance = np.sqrt(lat_diff**2+long_diff**2)
    easyDistanceReader(Distance)
    return Distance

def easyDistanceReader(Distance):
    if Distance > 1000:
        Distance = Distance/1000
        print("Distance:", Distance, "km")
    else:
        print("Distance:", Distance, "m")


def runProgram(target_df, source_df, distans_threshold):
    
    """
    Loop over coord in source.csv 
        --> Find all the coordinates within the interval in target.csv
    """
    
    "Using this in order to skip coordinates in source.csv which are outside the target.csv     area"
    latInterval = min(target_df['lat2']), max(target_df['lat2'])
    longInterval = min(target_df['long2']), max(target_df['long2'])
    
    "Find all relevant coordinates based on the source coordinates"
    source_df = source_df.loc[(source_df['lat1'].between(min(latInterval), max(latInterval))) &     (source_df['long1'].between(min(longInterval), max(longInterval)))]

    dataframes = []
    start = time.time()
    for index in range(len(source_df)):
        row = source_df.iloc[index]
        source_coordinates = row[['lat1','long1']]
        
        indices = []
        target_df = target_df.apply(findDistance, args=(row['lat1'],row['long1']), axis=1)
        
        relevantTargets = target_df.loc[target_df['Distance'] < distans_threshold]
        if len(relevantTargets) > 0:
            indices.append(relevantTargets.index[0])

        if len(indices) > 0:
            new_df = target_df.loc[indices]
            dataframes.append(new_df)
        
    final_df = pd.concat(dataframes)


    final_df = final_df.loc[:, final_df.columns != 'Distance'].drop_duplicates()
    print(final_df)
    
    end = time.time()
    print("Elapsed time per iteration:", end-start)
    
    final_df.to_csv('final.csv')
    playsound('audio.mp3')

runProgram(fast_df,el_df, 300) # This number indicates the distance in meters from source coordinates I want to find target coordinates.

我目前得到的结果是this。这是我在 5000 米处运行代码时的结果。您可以清楚地看到很多坐标点都被遗漏了,我不知道为什么。黑点是点,棕色目标点和粉红色是结果点。

任何想法将不胜感激!

【问题讨论】:

  • 我已经回答了类似的问题。看看BallTree 和这个answer。您只需将tree.query(coords, k=1) 更改为tree.query_radius(coords, r=5000, return_distance=True)。请提供示例和预期输出。

标签: python pandas csv coordinates gis


【解决方案1】:

当您想要所有相关目标的索引时,indices.append(relevantTargets.index[0]) 行仅附加相关目标的第一个索引。尝试将其替换为 indices += [*relevantTargets.index]。但是,我不知道为什么你不能直接在这里做dataframes.append(relevantTargets)

【讨论】:

  • 工作就像一个魅力!非常感谢人!我的帐户太新手了,所以我什至不能给你点赞。 :
【解决方案2】:

如果我正确地考虑了您的问题,则可以使用 GeoPandas.sjoin_nearest [link here] 简化此方法。我过去曾使用 geopandas.sjoin 模块将点连接到相交的多边形。我相信 sjoin_nearest 刚刚添加到最新版本中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多