TransWikia.com

Geopandas TypeError when saving a GeoDataFrame after creating CategoricalDtype

Geographic Information Systems Asked by B Furtado on March 25, 2021

I’m trying to prepare a column classification of a GeoDataFrame before exporting to QGIS. So, I use pandas.cut. However, when I want to save it I get a

 TypeError: Cannot interpret 'CategoricalDtype(categories=[...list categories...],
                 ordered=True)' as a data type

Here is a reproducible example.

import geopandas as gpd
import numpy as np
import pandas as pd
from shapely.geometry import Point

gdf = gpd.GeoDataFrame({'value': np.random.randint(0, 100, 20),
                        'geometry': [Point(x, y) for x, y in zip(np.random.randint(0, 100, 20),
                                                                 np.random.randint(0, 100, 20))]})
labels = ["{0} - {1}".format(i, i + 9) for i in range(0, 100, 10)]
gdf['group'] = pd.cut(gdf.value, range(0, 105, 10), right=False, labels=labels)
gdf.to_file('t.shp')

One Answer

Categorical is not a data type shapefiles can handle. Convert it to string:

gdf['group'] = pd.cut(gdf.value, range(0, 105, 10), right=False, labels=labels).astype(str)

Correct answer by BERA on March 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP