Last active
June 18, 2022 11:47
-
-
Save ThomasG77/1c76c8fd4f6ee08d9da88dfdb911cfcb to your computer and use it in GitHub Desktop.
Multiple approaches to solve question at https://lists.osgeo.org/pipermail/gdal-dev/2022-June/055949.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from osgeo import gdal | |
# gdal.UseExceptions() | |
# gdal.SetConfigOption('CPL_DEBUG', 'ON') | |
# Create a test CSV | |
file = "test.csv" | |
with open("test.csv", "w") as csv: | |
csv.write("latitude,longitude\n") | |
csv.write("61,-150") | |
# GDAL approach using gdal.VectorTranslate | |
ds = gdal.OpenEx( | |
file, open_options=["X_POSSIBLE_NAMES=longitude", "Y_POSSIBLE_NAMES=latitude"] | |
) | |
gdal.VectorTranslate( | |
"out.gpkg", ds, options='-f GPKG -a_srs "EPSG:4326" -nln layernameout' | |
) | |
# Geopandas approach | |
import geopandas | |
gdf = geopandas.read_file(file, x_possible_names="longitude", y_possible_names="latitude") | |
gdf.to_file("dataframe1.gpkg", driver="GPKG", crs='epsg:4326') | |
# Fiona approach | |
import fiona | |
cols_lon_lat = ["longitude", "latitude"] | |
with fiona.open(file) as infile: | |
properties = dict( | |
[[i, "str"] for i in infile.schema.get("properties") if i not in cols_lon_lat] | |
) | |
schema = {"geometry": "Point", "properties": properties} | |
with fiona.open( | |
"test_geopackage.gpkg", | |
"w", | |
driver="GPKG", | |
crs="EPSG:4326", | |
schema=schema, | |
layer="layername", | |
) as gpkg: | |
for _, row in infile.items(): | |
gpkg.write( | |
{ | |
"properties": { | |
k: v | |
for k, v in row.get("properties").items() | |
if k not in cols_lon_lat | |
}, | |
"geometry": { | |
"type": "Point", | |
"coordinates": [ | |
float(row.get("properties").get(col)) | |
for col in cols_lon_lat | |
], | |
}, | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Updated the gist. Do not forget the crs e.g
otherwise
ogrinfo -so -al dataframe.gpkg
output the followinginstead of