3

I would like to convert my DataFrame to GeoDataFrame, but every post is about points. I need to convert polygons. Coordinates are in df['geometry']. How can I do that?

My DataFrame is below:

I was trying:

df = gpd.GeoDataFrame(df, geometry='geometry')

But I'am getting error:

TypeError: Input must be valid geometry objects: 495495.84 516704.74 495487.95 516706.54 495490.65 516718.33 495498.54 516716.52 495495.84 516704.74

enter image description here

3
  • 2
    The figure is unreadable, try to write the results. What have you tried because unless you add a Python code attempt your question will be closed. – gene Jan 7 at 15:28
  • I don't know how to start. – datasciencebegginer Jan 7 at 15:38
  • I'am getting error "shapely.errors.WKTReadingError: Could not create geometry because of errors while reading input." – datasciencebegginer Jan 7 at 17:59
6

geometry column is not in WKT format. Therefore you need a custom method similar to geopandas.point_from_xy. You can use the following script. polygons_from_custom_xy_string method is a string-specific. In case of the geometry column has different xy string (for example 'x y, x y, ..'), you should modify s.split() in xy_list_from_string method.

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

def polygons_from_custom_xy_string(df_column):
    
    def chunks(lst, n):
        for i in range(0, len(lst), n):
            yield lst[i:i + n]
    
    def xy_list_from_string(s):
        # 'x y x y ...' -> [[x, y], [x, y], ...]
        return list(chunks([float(i) for i in s.split()], 2))
    
    def poly(s):
        """ returns shapely polygon from point list"""
        ps = xy_list_from_string(s)
        return Polygon([[p[0], p[1]] for p in ps])

    polygons = [poly(r) for r in df_column]

    return polygons


df = pd.read_csv("file/path")

gdf = gpd.GeoDataFrame(df, geometry=polygons_from_custom_xy_string(df["geometry"]))

gdf.plot()

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