【问题标题】:Error while looping on polygon geopandas column, within() function not working在多边形 geopandas 列上循环时出错,within() 函数不起作用
【发布时间】:2022-01-15 06:15:49
【问题描述】:

我有一个带有多边形的数据框,并且想循环创建一个新列,以检查特定点是否在一个或多个多边形内(因为它们不是排他的)。我尝试按照 geopandas 教程进行操作,但这似乎不起作用,因为所有列都返回“False”。可以请指出我做错了什么吗? 非常感谢。 以防万一,文件“quartier_paris.geojson”是一个经典的geojson文件,读取它没有问题(形状出现,我可以去所有quartiers.explore(),例如,查看地图上的所有多边形,我是100%肯定该点在这些多边形内。文件的大小太大而无法加载,这是它的链接以防万一https://parisdata.opendatasoft.com/explore/dataset/quartier_paris/download/?format=geojson&timezone=Europe/Berlin&lang=fr)

import pandas as pd
import geopandas
import os
import shapely
from shapely.geometry import Polygon, LineString, Point

quartiers = geopandas.read_file("quartier_paris.geojson")
p1 = Point(48.823, 2.30)  
quartiers["Match"] =quartiers["geometry"].apply(lambda x: p1.within(x))


【问题讨论】:

    标签: python pandas geopandas shapely


    【解决方案1】:
    • 您的观点不在任何几何图形中。此外,您还调换了经度和纬度
    • 转置时位于几何的矩形边界内
    • 下面的代码显示了测试和一个 plotly 地图框来演示
    import requests
    import geopandas as gpd
    from shapely.geometry import Polygon, LineString, Point, box
    import plotly.express as px
    import plotly.graph_objects as go
    
    res = requests.get(
        "https://parisdata.opendatasoft.com/explore/dataset/quartier_paris/download/?format=geojson&timezone=Europe/Berlin&lang=fr"
    )
    gdf = gpd.GeoDataFrame.from_features(res.json())
    p1 = Point(48.823, 2.30)
    p2 = Point(2.30, 48.823)
    
    print(
        f"""
    p1 in total bounds: {p1.within(box(*gdf.total_bounds))}
    p2 in total bounds: {p2.within(box(*gdf.total_bounds))}
    p2 in any geometry: gdf["geometry"].apply(lambda g: p2.within(g)).any()
    """
    )
    
    px.scatter_mapbox(lon=[p2.x], lat=[p2.y]).update_layout(
        mapbox={
            "style": "carto-positron",
            "zoom": 10,
            "layers": [
                {"source": gdf["geometry"].__geo_interface__, "type": "line"},
                {
                    "source": gdf["geometry"]
                    .apply(lambda g: box(*g.bounds))
                    .__geo_interface__,
                    "type": "line",
                    "color": "skyblue",
                },
                {
                    "source": box(*gdf.total_bounds).__geo_interface__,
                    "type": "line",
                    "color": "blue",
                },
            ],
        },
        margin={"l": 0, "r": 0, "t": 0, "b": 0},
    ).update_traces(marker_size=20)
    

    猜你喜欢
    • 2022-01-25
    • 2021-12-26
    • 2018-06-14
    • 1970-01-01
    • 2021-04-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多