Convertendo DataFrame com coluna geométrica em GeoDataFrame em Pandas

Oct 09 2020

Eu tenho este DataFrame:

In [120]: a
Out[120]: 
     a    b              c
0  111  333  [POINT (0 0)]
1  222  444  [POINT (0 0)]

Estou tentando converter com a próxima linha, mas falha:

In [125]: b = gpd.GeoDataFrame(a[['a', 'b']], geometry=list(a['c']))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-125-cce5399870e4> in <module>
----> 1 b = gpd.GeoDataFrame(a[['a', 'b']], geometry=list(a['c']))

/usr/local/lib/python3.8/dist-packages/geopandas/geodataframe.py in __init__(self, *args, **kwargs)
    149                 )
    150                 # TODO: raise error in 0.9 or 0.10.
--> 151             self.set_geometry(geometry, inplace=True)
    152         self._invalidate_sindex()
    153 

/usr/local/lib/python3.8/dist-packages/geopandas/geodataframe.py in set_geometry(self, col, drop, inplace, crs)
    252 
    253         # Check that we are using a listlike of geometries
--> 254         level = _ensure_geometry(level, crs=crs)
    255         index = frame.index
    256         frame[geo_column_name] = level

/usr/local/lib/python3.8/dist-packages/geopandas/geodataframe.py in _ensure_geometry(data, crs)
     40             return GeoSeries(out, index=data.index, name=data.name)
     41         else:
---> 42             out = from_shapely(data, crs=crs)
     43             return out
     44 

/usr/local/lib/python3.8/dist-packages/geopandas/array.py in from_shapely(data, crs)
    164 
    165     """
--> 166     return GeometryArray(vectorized.from_shapely(data), crs=crs)
    167 
    168 

/usr/local/lib/python3.8/dist-packages/geopandas/_vectorized.py in from_shapely(data)
    132             out.append(None)
    133         else:
--> 134             raise TypeError("Input must be valid geometry objects: {0}".format(geom))
    135 
    136     if compat.USE_PYGEOS:

TypeError: Input must be valid geometry objects: <GeometryArray>
[<shapely.geometry.point.Point object at 0x7f80af64beb0>]
Length: 1, dtype: geometry

Não sei como converter a lista ou série (dataframe) em GeometryArray.

Estou tentando com: gpd.array.GeometryArray(list(a['c']))mas não está funcionando.

Respostas

4 martinfleis Oct 09 2020 at 08:47

Cada uma de suas geometrias está dentro de uma lista, portanto, você está efetivamente passando uma lista de listas como uma geometria para GeoDataFrame. Você tem que passar uma lista de geometrias, não listas.

Usando a aplicação, você pode obter a geometria real da lista.

b = gpd.GeoDataFrame(a[['a', 'b']], geometry=a['c'].apply(lambda x: x[0])