Fiona – Changing Shapefile’s Field Type Using Fiona

fionapythonshapefiletime

I need to have a layer time-enabled for Esri application-making. Coming from the source, it has an int type column called year. I need to find a way to automate its conversion to date.

I first tried with Geopandas, but it gives a ValueError if I try and save to Shapefile with a datetime[ms] dtype:

ValueError: Invalid field type <class 'pandas.tslib.Timestamp'>

I know Fiona can handle date, time, and datetime field types though:

>>> fiona.FIELD_TYPES_MAP

{'date': fiona.rfc3339.FionaDateType,
 'datetime': fiona.rfc3339.FionaDateTimeType,
 'float': float,
 'int': int,
 'str': str,
 'time': fiona.rfc3339.FionaTimeType}

When I load it with Fiona I get:

{'geometry': 'Point',
 'properties': OrderedDict([('npri_id', 'int:9'),
              ('facility', 'str:80'),
              ('year', 'int:9'),
              ...])}

How would I go about changing it to date?

Best Answer

You can automate it with geopandas, but there seems to be an issue in automatically converting the pandas datetime objects to the right properties schema. Fortunately, as geopandas is built directly on top of fiona for reading and writing you can specify a schema for writing output, e.g.:

schema = {
    'geometry': 'Point',
    'properties': {
        'npri_id': 'int',
        'facility': 'str',
        'year': 'datetime',
}}

geodataframe.to_file('output.shp', schema=schema)

Note that the number of fields in the schema must match the number of fields in the geodataframe to export (though you can of course subset the fields to export).

Related Question