4

My current dataframe (clean_geoms) contains two columns (field_geom_type, field_coords) that I want to convert to a single geometry (GeoSeries)

This is a representative sample of my data:

print(clean_geoms.field_geom_type.iloc[0])
print(clean_geoms.field_coords.iloc[0])

Polygon
[[[-96.568927, 46.769008], [-96.5689454, 46.7705433], [-96.5726564, 46.7705222], [-96.572638, 46.7689868], [-96.568927, 46.769008]]]

What is the best way to unpack this list so that it can be converted into geometry?

1
  • A list of lists of lists already is the best way to convert any geometry (including multi-part geometries and polygons with sub-parts)
    – Vince
    Jun 11 '20 at 22:03
5

Using built-in eval method is handful in this situation.

import pandas as pd
import geopandas as gpd
from shapely.geometry import Polygon

clean_geoms = pd.DataFrame([["Polygon", "[[[-96.568927, 46.769008], [-96.5689454, 46.7705433], [-96.5726564, 46.7705222], [-96.572638, 46.7689868], [-96.568927, 46.769008]]]"]],
                           columns=["field_geom_type", "field_coords"])
print(clean_geoms)

# OUTPUT
#    field_geom_type  field_coords
# 0  Polygon          [[[-96.568927, 46.769008], [-96.5689454, 46.77...


data = Polygon(eval(clean_geoms.field_coords.iloc[0])[0])
gdf = gpd.GeoSeries(data)
print(gdf)

# OUTPUT
# 0    POLYGON ((-96.56893 46.76901, -96.56895 46.770...
# dtype: geometry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.