[GIS] Convert ArcGIS Spatially Enabled Dataframe to Geopandas GeoDataFrame

arcgis-python-apigeopandas

I have some code that works on geopandas GeoDataFrames but due to a client requirement I suddenly have to access my input data via the ArcGIS Python library, which only allows me to access the data as an ArcGIS Spatially Enabled DataFrame.

Unsurprisingly, ESRI has only provided methods to convert from geopandas to their format, and provided no support for the opposite direction:

https://developers.arcgis.com/python/api-reference/arcgis.features.toc.html#arcgis.features.GeoAccessor.from_geodataframe

https://community.esri.com/t5/arcgis-api-for-python-questions/creating-updating-feature-layer-in-arcgis-online-from-geopandas/td-p/790989

Is there a way to easily convert one of these to a geopandas GeoDataFrame or am I now locked in the ESRI prison?

I guess I could temporarily write the results to the file system and then open it with geopandas from there, but I am hoping it doesn't come to that.

Best Answer

While there is no method in the ArcGIS Python API to convert from a SpatialDataFrame to a Geopandas GeoDataFrame, we can create a GeoDataFrame using another method.

I will assume you are accessing your ArcGIS Online feature layer using the .query() method, which returns a FeatureSet. You can convert a FeatureSet into a geojson string, read the geojson as a dict, and construct a GeoDataFrame from that dict.

from arcgis.gis import GIS
import geopandas as gpd
import json

# login to AGOL
gis = GIS('https://arcgis.com', username, password)

# get the hosted feature layer
flayer = gis.content.get('identifierstring').layers[0]

# .query() returns a FeatureSet
fset = flayer.query()

# get a GeoJSON string representation of the FeatureSet
gjson_string = fset.to_geojson

# read GeoJSON string into a dict
gjson_dict = json.loads(gjson_string)

gdf = gpd.GeoDataFrame.from_features(gjson_dict['features'])
# may need to specify CRS and geometry column name after GeoDataFrame construction