gpt4 book ai didi

python - 使用 GeoPandas 的两个数据帧中的 K 最近点

转载 作者:行者123 更新时间:2023-12-01 23:59:02 25 4
gpt4 key购买 nike

GeoPandas 在底层使用 shapely。为了获得最近的邻居,我看到了使用 nearest_points from shapely .但是,这种方法不包括 k-最近点。

我需要计算从 GeoDataFrames 到最近点的距离,并将距离插入包含“从这一点开始”数据的 GeoDataFrame。

这是我使用 GeoSeries.distance() 而不使用其他包或库的方法。请注意,当 k == 1 时,返回值基本上显示到最近点的距离。 There is also a GeoPandas-only solution for nearest point by @cd98 which inspired my approach .

这对我的数据很有效,但我想知道是否有更好或更快的方法或使用 shapely 或 sklearn.neighbors 的其他好处?

import pandas as pd
import geopandas as gp

gdf1 > GeoDataFrame with point type geometry column - distance from this point
gdf2 > GeoDataFrame with point type geometry column - distance to this point

def knearest(from_points, to_points, k):
distlist = to_points.distance(from_points)
distlist.sort_values(ascending=True, inplace=True) # To have the closest ones first
return distlist[:k].mean()

# looping through a list of nearest points
for Ks in [1, 2, 3, 4, 5, 10]:
name = 'dist_to_closest_' + str(Ks) # to set column name
gdf1[name] = gdf1.geometry.apply(knearest, args=(gdf2, closest_x))

最佳答案

是的,但首先,我必须将 automating GIS process 归功于赫尔辛基大学, 这里是 the source code .方法如下
首先,读取数据,例如,为每个建筑物找到最近的公共(public)汽车站。

# Filepaths
stops = gpd.read_file('data/pt_stops_helsinki.gpkg')
buildings = read_gdf_from_zip('data/building_points_helsinki.zip')

定义函数,这里可以调整k_neighbors

from sklearn.neighbors import BallTree
import numpy as np

def get_nearest(src_points, candidates, k_neighbors=1):
"""Find nearest neighbors for all source points from a set of candidate points"""

# Create tree from the candidate points
tree = BallTree(candidates, leaf_size=15, metric='haversine')

# Find closest points and distances
distances, indices = tree.query(src_points, k=k_neighbors)

# Transpose to get distances and indices into arrays
distances = distances.transpose()
indices = indices.transpose()

# Get closest indices and distances (i.e. array at index 0)
# note: for the second closest points, you would take index 1, etc.
closest = indices[0]
closest_dist = distances[0]

# Return indices and distances
return (closest, closest_dist)


def nearest_neighbor(left_gdf, right_gdf, return_dist=False):
"""
For each point in left_gdf, find closest point in right GeoDataFrame and return them.

NOTICE: Assumes that the input Points are in WGS84 projection (lat/lon).
"""

left_geom_col = left_gdf.geometry.name
right_geom_col = right_gdf.geometry.name

# Ensure that index in right gdf is formed of sequential numbers
right = right_gdf.copy().reset_index(drop=True)

# Parse coordinates from points and insert them into a numpy array as RADIANS
left_radians = np.array(left_gdf[left_geom_col].apply(lambda geom: (geom.x * np.pi / 180, geom.y * np.pi / 180)).to_list())
right_radians = np.array(right[right_geom_col].apply(lambda geom: (geom.x * np.pi / 180, geom.y * np.pi / 180)).to_list())

# Find the nearest points
# -----------------------
# closest ==> index in right_gdf that corresponds to the closest point
# dist ==> distance between the nearest neighbors (in meters)

closest, dist = get_nearest(src_points=left_radians, candidates=right_radians)

# Return points from right GeoDataFrame that are closest to points in left GeoDataFrame
closest_points = right.loc[closest]

# Ensure that the index corresponds the one in left_gdf
closest_points = closest_points.reset_index(drop=True)

# Add distance if requested
if return_dist:
# Convert to meters from radians
earth_radius = 6371000 # meters
closest_points['distance'] = dist * earth_radius

return closest_points

做最近邻分析

# Find closest public transport stop for each building and get also the distance based on haversine distance
# Note: haversine distance which is implemented here is a bit slower than using e.g. 'euclidean' metric
# but useful as we get the distance between points in meters
closest_stops = nearest_neighbor(buildings, stops, return_dist=True)

现在加入 from 和 to 数据框

# Rename the geometry of closest stops gdf so that we can easily identify it
closest_stops = closest_stops.rename(columns={'geometry': 'closest_stop_geom'})

# Merge the datasets by index (for this, it is good to use '.join()' -function)
buildings = buildings.join(closest_stops)

关于python - 使用 GeoPandas 的两个数据帧中的 K 最近点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com