You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OSMNX使用features模块遇无结果时,如何获取空DataFrame?

关于OSMnx无结果时抛出错误的问题解答

核心问题说明

当使用ox.features_from_polygon搜索无匹配结果时抛出InsufficientResponseError是OSMnx v1.0+版本的预期行为。在2023年的旧版本(v0.x系列)中,确实会返回空GeoDataFrame,这是版本迭代后的行为变更。

代码中的明显错误

你的循环代码存在变量名误用问题:循环变量是municipalities,但request_dict里的"city"值写的是commune_with_hotels,这会导致每次循环都用同一个(未定义的)值请求边界,修正后应该是:

for municipality in ['Aarau', 'Acquarossa']:
    request_dict = {
        "city": municipality,  # 这里改为当前循环的市镇名
        "country": "Switzerland",
        "countrycodes": "ch",
    }
    # 后续代码不变

如何获取空DataFrame

要在无结果时返回空GeoDataFrame,需要通过try/except捕获InsufficientResponseError,并手动创建结构匹配的空GeoDataFrame。示例代码如下:

import osmnx as ox
from osmnx._errors import InsufficientResponseError
import geopandas as gpd

def get_features_with_fallback(polygon, tags):
    try:
        return ox.features_from_polygon(polygon, tags)
    except InsufficientResponseError:
        # 创建空GeoDataFrame,匹配features_from_polygon的输出结构
        empty_gdf = gpd.GeoDataFrame(
            columns=['osmid', 'name', 'geometry'],  # 包含常见字段,可根据需求调整
            geometry='geometry',
            crs="EPSG:4326"
        )
        return empty_gdf

# 修正后的循环逻辑
for municipality in ['Aarau', 'Acquarossa']:
    request_dict = {
        "city": municipality,
        "country": "Switzerland",
        "countrycodes": "ch",
    }
    request = ox.geocode_to_gdf(request_dict)
    boundary_polygon = request["geometry"][0]
    
    hotels_per_commune = get_features_with_fallback(boundary_polygon, {"tourism": "hotel"})
    motels_per_commune = get_features_with_fallback(boundary_polygon, {"tourism": "motel"})
    
    # 后续处理逻辑示例
    print(f"{municipality} - 酒店数量: {len(hotels_per_commune)}, 汽车旅馆数量: {len(motels_per_commune)}")

补充说明

  • 捕获错误后创建的空GeoDataFrame,可根据实际需求添加更多字段(比如tourism、addr:city等),确保和有结果时的输出结构一致,避免后续处理报错。
  • 可通过ox.__version__查看当前OSMnx版本,v1.0+的错误处理逻辑更严格,目的是明确告知用户查询无结果,而非静默返回空值。

内容的提问来源于stack exchange,提问作者Antonin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:52:37