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

如何将geopandas中geolib的Bounds类型转换为Polygon几何类型?

将geolib.geohash.Bounds转换为GeoPandas的Polygon几何类型

我有一个包含geolib.geohash.Bounds类型数据的GeoPandas DataFrame,示例代码如下:

import pandas as pd
import geopandas as gpd

gdf = gpd.GeoDataFrame({
                        'id': [0, 1],
                        'b': [((40.6494140625, -86.7919921875), (40.69335937...)), 
                              ((39.55078125, -93.8232421875), (39.5947265625...))]
                      })

# 查看单个Bounds对象
gdf['b'][0]
# 输出:Bounds(sw=SouthWest(lat=32.8271484375, lon=-96.8115234375), ne=NorthEast(lat=32.87109375, lon=-96.767578125))

print(type(gdf['b'][0]))
# 输出:<class 'geolib.geohash.Bounds'>

我需要将这些Bounds类型的对象转换为GeoPandas支持的Polygon几何类型,期望得到类似如下格式的结果:

Polygon((40.6494140625, -86.7919921875), (40.69335937...), ...)

解决方案

利用shapely库构造Polygon,具体步骤如下:

  1. 导入shapely.geometry.Polygon(GeoPandas几何类型基于shapely);
  2. 编写转换函数,从Bounds对象提取西南(sw)、东北(ne)顶点的经纬度,构造矩形Polygon的闭合顶点序列;
  3. 将函数应用到DataFrame目标列,生成Polygon类型的几何列。

完整代码示例:

import pandas as pd
import geopandas as gpd
from shapely.geometry import Polygon
from geolib.geohash import Bounds, SouthWest, NorthEast  # 导入所需类

# 构造示例数据
gdf = gpd.GeoDataFrame({
    'id': [0, 1],
    'b': [
        Bounds(sw=SouthWest(lat=32.8271484375, lon=-96.8115234375), ne=NorthEast(lat=32.87109375, lon=-96.767578125)),
        Bounds(sw=SouthWest(lat=39.55078125, lon=-93.8232421875), ne=NorthEast(lat=39.5947265625, lon=-93.779296875))
    ]
})

# 定义Bounds转Polygon的函数
def bounds_to_polygon(bounds_obj):
    # 提取经纬度注意:Bounds是lat在前,shapely是lon在前,需调换顺序
    sw_lon, sw_lat = bounds_obj.sw.lon, bounds_obj.sw.lat
    ne_lon, ne_lat = bounds_obj.ne.lon, bounds_obj.ne.lat
    # 构造闭合的矩形顶点序列
    coords = [
        (sw_lon, sw_lat),
        (sw_lon, ne_lat),
        (ne_lon, ne_lat),
        (ne_lon, sw_lat),
        (sw_lon, sw_lat)  # 回到起点,确保多边形闭合
    ]
    return Polygon(coords)

# 应用转换函数生成几何列
gdf['geometry'] = gdf['b'].apply(bounds_to_polygon)

# 将生成的列设为GeoDataFrame的官方几何列
gdf = gpd.GeoDataFrame(gdf, geometry='geometry')

# 查看转换结果
print(gdf['geometry'][0])

关键注意点

  • 坐标顺序:shapely的Polygon采用(经度, 纬度)顺序,而Bounds对象的属性是lat在前,转换时必须调换顺序;
  • 多边形闭合:构造Polygon的坐标列表必须以起始点结尾,保证图形是闭合的环形;
  • GeoDataFrame规范:将转换后的列设为官方几何列后,才能正常使用GeoPandas的空间分析、绘图等功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:42:30