31

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,....
emax
  • 6,965
  • 19
  • 74
  • 141

4 Answers4

35

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'
ffrosch
  • 899
  • 6
  • 15
29

You could also try this:

gdf = gpd.GeoDataFrame(
    df, geometry=gpd.points_from_xy(df.longitude, df.latitude)
)

This will convert those lat/long columns to points

James
  • 32,991
  • 4
  • 47
  • 70
SKhan2312
  • 297
  • 3
  • 3
  • 1
    But where within the dataframe presented are the columns latitude and longitude? – shadow_dev Jul 09 '20 at 21:43
  • 1
    The correct order when using geometric coordinates with `points_from_xy` is `points_from_xy(longitudes, latitudes)`. – mins Jan 04 '22 at 14:25
1

Dudes, there are wkt geometry strings in the original dataframe, not xy columns, so i would suggest read this: DataFrame with WKT Column to GeoPandas Geometry

sal
  • 1,199
  • 1
  • 13
  • 31
0

Geopandas puts a geometry column at the end if you load directly. Found this out by experimenting with column names and it worked