GeoPandas – Fixing AttributeError When Field Names Are Tuples

centroidsdissolvefionageopandaspython

I have created a new shapefile by dissolving and computing centroids from an existing shapefile. I have also aggregated values of the existing shapefile to use in the new shapefile. However, when I try to save the new shapefile, I get the error:

AttributeError: 'tuple' object has no attribute 'encode'.

I understand that this is because I want to save both the first and last value of one of the attributes ('openbare_r') in the dissolved file. This results in GeoPandas making my field names into tuples, leading to this error. How do I convert the tuples back into regular field names, or how else can I solve it?

dissolved = open_woonbestand.dissolve(by='postcode',aggfunc={
    'bouwjaar':'mean',
    'oppervlakt':'mean',
    'openbare_r':['first','last'],
    }
    )

centroids = dissolved.centroid
dissolved['geometry'] = dissolved.geometry.centroid

print(list(dissolved.columns.values))
dissolved.to_file(outpath)

This prints:

['geometry', ('bouwjaar', 'mean'), ('oppervlakt', 'mean'), ('openbare_r', 'first'), ('openbare_r', 'last')]

If I don't aggregate both the first and last value of openbare_r, but instead just the first, it works, because then it has single field names:

['geometry', 'bouwjaar', 'oppervlakt', 'openbare_r']

Best Answer

Convert field names to string

dissolved.columns = [field_name[0] + "_" + field_name[1] if type(field_name) is tuple else field_name for field_name in list(dissolved.columns.values)]

Reproducible example

import geopandas
from shapely.geometry import Point
d = {("col1", "mean"): ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")
gdf.columns = [field_name[0] + "_" + field_name[1] if type(field_name) is tuple else field_name for field_name in list(gdf.columns.values)]