TransWikia.com

Converting DataFrame with geometry column into GeoDataFrame in Pandas

Geographic Information Systems Asked on August 2, 2021

I have this DataFrame:

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

I am trying to convert with the next line, but it fails:

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

I don’t know how I convert the list or series (dataframe) to GeometryArray.

I am trying with: gpd.array.GeometryArray(list(a['c'])) but it is not working.

One Answer

Each of you geometries is within a list, so you are effectively passing a list of lists as a geometry to GeoDataFrame. You have to pass a list-like of geometries, not lists.

Using apply you can get the actual geometry out of the list.

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

Correct answer by martinfleis on August 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP