首页 > 解决方案 > 几何类型多多边形与列类型多边形不匹配

问题描述

使用 python、sqlalchemy 和 psycopg2 驱动程序,我试图从一个 shapefile 到一个地理数据框,再到一个在这个问题之后安装了 postgis 的 postgres 数据库

我将几何图形转换为 WKB 十六进制字符串,并df.to_sql()成功使用导入的标准数据框。

运行alter table查询时出现错误:

sqlalchemy.exc.DataError: (psycopg2.errors.InvalidParameterValue) Geometry type (MultiPolygon) does not match column type (Polygon)

标签: pythonpostgisgeoalchemy

解决方案


重写了@Hugh_Kelley 的函数以更快。

def _explode(indf):
    count_mp = 0
    outdf = gpd.GeoDataFrame(columns=indf.columns)
    outdf = indf[indf.geometry.type == 'Polygon']
    indf = indf[indf.geometry.type != 'Polygon']
    for idx, row in indf.iterrows():
        if type(row.geometry) == MultiPolygon:
            count_mp = count_mp + 1
            multdf = gpd.GeoDataFrame(columns=indf.columns)
            recs = len(row.geometry)
            multdf = multdf.append([row]*recs,ignore_index=True)
            for geom in range(recs):
                multdf.loc[geom,'geometry'] = row.geometry[geom]
            outdf = outdf.append(multdf,ignore_index=True)
        else:
            print(row)
    print("There were ", count_mp, "Multipolygons found and exploded")
    return outdf

推荐阅读