Writing Data
Spatial polars provides an few options to write dataframes to spatial formats. Like reading data, spatial polars uses pyogrio under the hood when using the write_spatial
method to write data, so anything it can write should be fine.
Spatial polars can also write to geoparquet with help from GeoArrow Python using the write_geoparquet
method.
Note
This example makes use the geodatasets python package to access some spatial data easily.
Calling geodatasets.get_path()
will download data the specified data to the machine and return the path to the downloaded file. If the file has already been downloaded it will simply return the path to the file.
See downloading and caching for further details.
Before we can write something, we need something to write, so we'll read some data from the geodatasets package into a dataframe.
import os
import tempfile
import geodatasets
from spatial_polars import read_spatial
df = read_spatial(geodatasets.get_path("geoda.chicago_commpop"))
Writing to a shapefile
The following example will demonstrate how easy it is to write data to an ESRI Shapefile in your temporary directory.
output_shp_path = os.path.join(tempfile.gettempdir(), "spatial_polars.shp")
df.spatial.write_spatial(output_shp_path)
print(f"Wrote dataframe to {output_shp_path}")
Writing to a geopackage
The example will demonstrate how to write data to a geopackage.
You'll notice that this is slightly more complicated than writing to a shapefile because a geopackage can store more than one table, so we need to provide the name for the table to the layer
parameter.
output_gpkg_path = os.path.join(tempfile.gettempdir(), "spatial_polars.gpkg")
df.spatial.write_spatial(output_gpkg_path, layer="chicago_commpop")
print(f"Wrote dataframe to {output_gpkg_path}")
Appending to an existing dataset
Additionaly, many formats also support appending new records to an existing dataset. This is done simply by adding append=True
to our write_spatial
call.
df.spatial.write_spatial(output_gpkg_path, layer="chicago_commpop", append=True)
Writing to geoparquet
The following example will demonstrate how to write data to a geoparquet file.