geopandas.GeoDataFrame.sjoin_nearest#

GeoDataFrame.sjoin_nearest(right, how='inner', max_distance=None, lsuffix='left', rsuffix='right', distance_col=None)#

基于两个GeoDataFrame几何图形之间的距离进行空间连接。

结果将包括单个输入记录的多个输出记录,其中存在多个等距离、最近的或相交的邻居。

有关更多详细信息,请参阅用户指南页面https://geopandas.readthedocs.io/en/latest/docs/user_guide/mergingdata.html。

参数
rightGeoDataFrame
how字符串,缺省为‘内部’

联接的类型:

  • ‘Left’:使用Left_df中的键;仅保留Left_df几何列

  • ‘right’:使用right_df中的密钥;仅保留right_df几何列

  • ‘ner’:使用来自两个DFS的键的交集;仅保留LEFT_DF几何列

max_distance浮动,默认为无

查询最近几何图形的最大距离。必须大于0。通过减少为树中最近的项目求值的输入几何体的数量,用于在树中搜索最近项的max_Distance可能会对性能产生重大影响。

lsuffix字符串,默认为‘Left’

应用于重叠列名的后缀(左GeoDataFrame)。

rsuffix字符串,默认为‘Right’

应用于重叠列名的后缀(右GeoDataFrame)。

distance_col字符串,默认为无

如果设置,则将计算的匹配几何图形之间的距离保存在关联的GeoDataFrame中此名称的列下。

参见

GeoDataFrame.sjoin

二元谓词连接

sjoin_nearest

等价顶层函数

注意事项

由于此连接依赖于距离,因此如果几何图形位于地理CRS中,则结果将不准确。

GeoPandas中的每个操作都是平面的,即没有考虑潜在的第三维。

示例

>>> countries = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))
>>> cities = geopandas.read_file(geopandas.datasets.get_path("naturalearth_cities"))
>>> countries.head(2).name  
    pop_est      continent                      name     iso_a3  gdp_md_est                                           geometry
0     920938        Oceania                      Fiji    FJI      8374.0  MULTI    POLYGON (((180.00000 -16.06713, 180.00000...
1   53950935         Africa                  Tanzania    TZA    150600.0  POLYG    ON ((33.90371 -0.95000, 34.07262 -1.05982...
>>> cities.head(2).name  
        name                   geometry
0  Vatican City  POINT (12.45339 41.90328)
1    San Marino  POINT (12.44177 43.93610)
>>> cities_w_country_data = cities.sjoin_nearest(countries)
>>> cities_w_country_data[['name_left', 'name_right']].head(2)  
        name_left                   geometry  index_right   pop_est continent n    ame_right iso_a3  gdp_md_est
0    Vatican City  POINT (12.45339 41.90328)          141  62137802    Europe          Italy    ITA   2221000.0
1      San Marino  POINT (12.44177 43.93610)          141  62137802    Europe          Italy    ITA   2221000.0

要包括距离,请执行以下操作:

>>> cities_w_country_data = cities.sjoin_nearest(countries, distance_col="distances")
>>> cities_w_country_data[["name_left", "name_right", "distances"]].head(2)  
        name_left name_right distances
0    Vatican City      Italy       0.0
1      San Marino      Italy       0.0

在下面的示例中,我们获得了意大利的多个城市,因为所有结果都是等距离的(在本例中为零,因为它们相交)。事实上,我们总共得到了3个结果:

>>> countries_w_city_data = cities.sjoin_nearest(countries, distance_col="distances", how="right")
>>> italy_results = countries_w_city_data[countries_w_city_data["name_left"] == "Italy"]
>>> italy_results  
    name_x        name_y
141  Vatican City  Italy
141    San Marino  Italy
141          Rome  Italy