Waleed S Khan
Waleed S Khan

Reputation: 150

geopandas GeoDataFrame gets converted to pandas DataFrame with gdf.astype()

I have a geopandas GeoDataFrame with multiple columns. When I try to set data types for geoDataFrame columns, it returns a pandas DataFrame. Is there a way to return a GeoDataFrame object?

I have made a workaround in which I change the DataFrame back to a geoDataFrame after setting the data types of columns. But I am just interested in knowing if there is a way to return a GeoDataFrame. The code that I have is below:

gdf_voronoi = gdf_voronoi.astype({'elec_neighbors': object, 'trans_lines': object, 'Cap': float, 'Ratio': float,'Area': float})

geo_list = gdf_voronoi['geometry'].tolist()
gdf_voronoi = gpd.GeoDataFrame(gdf_voronoi, crs=crs, geometry=geo_list)

Any help would be great!

Upvotes: 5

Views: 4106

Answers (1)

joris
joris

Reputation: 139162

That's a bug in GeoPandas/pandas, for which I opened an issue here: https://github.com/geopandas/geopandas/issues/1006. So in the short term, you will need to keep your workaround to convert back to a GeoDataFrame afterwards.

Note that for converting the result back to a GeoDataFrame, you don't need to convert the geometries to a list. Specifying the geometry column name is enough, like:

gdf_voronoi = gdf_voronoi.astype(...)
gdf_voronoi = geopandas.GeoDataFrame(gdf_voronoi, geometry='geometry', crs=crs)

or since 'geometry' is the default, in this case you can even leave that out:

gdf_voronoi = gdf_voronoi.astype(...)
gdf_voronoi = geopandas.GeoDataFrame(gdf_voronoi, crs=crs)

Upvotes: 5

Related Questions