1

I have a GeoDataFrame gdf. I write its contents to a GeoJSON:

gdf.to_file("example.geojson")

which works. However, each geometry is specified to 16 significant figures, which is an overkill in my case.

How can I decrease the number of significant figures?


One possible way to do this is via ogr2ogr:

ogr2ogr example_fewer_digits.geojson example.geojson -lco COORDINATE_PRECISION=8

However, this still requires creating a file example.geojson and only then we can transform it to example_fewer_digits.geojson. If it was possible to achieve the same thing via GeoPandas only, it would be great.

Vince
  • 20,017
  • 15
  • 45
  • 64
zabop
  • 2,050
  • 7
  • 35

2 Answers2

1

When dealing with polygons, rounding coordinates is something to be handled with care, as the rounding can lead to self-intersections, parts collapsing to lines,...

The safe way to do this is to use shapely.set_precision. This function will round the coordinates but will also make sure the output is a valid geometry.

import shapely

Round the coordinates to 8 decimals

gdf.geometry = shapely.set_precision(gdf.geometry, grid_size=0.00000001)

In GeoPandas 1.0, planned to be released 31 march 2024, set_precision will also be available like this:

# Round the coordinates to 8 decimals
gdf.geometry = gdf.geometry.set_precision(grid_size=0.00000001)

Once the geometries are properly rounded, you can safely write them in that precision by specifying is to GDAL via pyogrio, as you wrote already in your answer:

gdf.to_file("example.geojson",engine='pyogrio',layer_options={"COORDINATE_PRECISION": 8})
Pieter
  • 1,876
  • 7
  • 9
0

You can use the pyogrio engine & the layer_options kwarg of to_file:

gdf.to_file("example.geojson",engine='pyogrio',layer_options={"COORDINATE_PRECISION": 8})
zabop
  • 2,050
  • 7
  • 35