Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Geopandas: how to read a csv and convert to a geopandas dataframe with polygons?

I read a .csv file as a dataframe that looks like the following:

import pandas as pd
df = pd.read_csv('myFile.csv')
df.head()
    BoroName    geometry
0   Brooklyn    MULTIPOLYGON (((-73.97604935657381 40.63127590...
1   Queens      MULTIPOLYGON (((-73.80379022888098 40.77561011...
2   Queens      MULTIPOLYGON (((-73.8610972440186 40.763664477...
3   Queens      MULTIPOLYGON (((-73.75725671509139 40.71813860...
4   Manhattan   MULTIPOLYGON (((-73.94607828674226 40.82126321...

I want to convert it to a geopandas dataframe.

import geopandas as gpd
crs = {'init': 'epsg:4326'}
gdf = gpd.GeoDataFrame(df, crs=crs).set_geometry('geometry')

but I get the following error

TypeError: Input must be valid geometry objects: MULTIPOLYGON (((-73.97604935657381 40.631275905646774, -73.97716511994669 40.63074665412933,....
like image 702
emax Avatar asked Sep 01 '25 02:09

emax


1 Answers

Geopandas seems to be unable to convert a geometry column from a pandas dataframe.

Solution number 2

Try applying the shapely wkt.loads function on your column before converting your dataframe to a geodataframe.

from shapely import wkt

df['geometry'] = df['geometry'].apply(wkt.loads)
gdf = gpd.GeoDataFrame(df, crs='epsg:4326')

Good luck!


Do not use - crashes spyder and jupyter kernel for some people

Solution number 1: Try loading the csv directly with geopandas

gdf = gpd.read_file('myFile.csv')
gdf.crs = 'epsg:4326'
like image 166
ffrosch Avatar answered Sep 02 '25 14:09

ffrosch