I have shp files that I would like to insert into a PostGIS database. I'm planning to use Geoalchemy2 and geopandas to do so. However, my data have the geometry types LINESTRING Z
and POINT Z
. As I don't know the geometry type of object, I used Geometry("GEOMETRY")
dtype as parameter of my to_sql
call.
I get the following error as a result:
(psycopg2.DataError) Geometry has Z dimension but column does not
Here is a functioning code:
from geoalchemy2 import Geometry, WKTElement
import geopandas as gpd
import sqlalchemy
engine = sqlalchemy.create_engine('postgresql://username:password@host:port/username')
gdf = gpd.read_file("file.shp")
gdf['geom'] = gdf['geometry'].apply(lambda x: WKTElement(x.wkt))
gdf.drop('geometry', 1, inplace=True)
gdf.to_sql(
"tablename",
engine,
if_exists='append',
index=False,
dtype={'geom': Geometry('Geometry', dimension=3)}
)
The dimension=3
parameter doesn't change anything.
I saw PostGIS Column has Z dimension but geometry does not, Geojson in postgis Geometry : Z dimension error and PostGIS error reads "Geometry has Z dimension but column does not" propositions but as I create the tables with the to_sql
command, I cannot alter the fields. I tried to alter the column afterwards and to insert then the 3D elements (e.g. LINESTRING Z (...)
) and that did work.
Do you think I should:
- Create the tables manually first by reading the columns?
- Stop looking for Python shp import and use something else (shp2pgsql)?
- Any other idea?