I have a geopandas dataframe of the type:
id \
0 028f342a-b26f-4e36-b5d1-25d3428cac2f
add
0 POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...
Here is the entire POLYGON:
;id;add
0;028f342a-b26f-4e36-b5d1-25d3428cac2f;POLYGON ((33.781475 3.5090296, 33.1241675 3.5090296, 33.1241675 4.392868066666667, 33.781475 4.392868066666667, 33.781475 3.5090296))
What I wish to do is to extract all x and y coordinates of the polygon corners into 2 columns. So, what I have tried is (This code is meant for the entire dataframe):
List_Mvv_id = list(set(df['id']))
Full =[]
for i in List_Mvv_id:
df = df[df['id']==i]
P = df['add'].iloc[0]
print(P)
for x,y in P.exterior.coords:
df['x'] = x
df['y'] = y
Full.append(df)
However, it only returns the first coordinates of the polygon:
id \
0 028f342a-b26f-4e36-b5d1-25d3428cac2f
0 028f342a-b26f-4e36-b5d1-25d3428cac2f
0 028f342a-b26f-4e36-b5d1-25d3428cac2f
0 028f342a-b26f-4e36-b5d1-25d3428cac2f
0 028f342a-b26f-4e36-b5d1-25d3428cac2f
add x y
0 POLYGON ((33.78148 3.50903, 33.12417 3.50903, ... 33.781475 3.50903
0 POLYGON ((33.78148 3.50903, 33.12417 3.50903, ... 33.781475 3.50903
0 POLYGON ((33.78148 3.50903, 33.12417 3.50903, ... 33.781475 3.50903
0 POLYGON ((33.78148 3.50903, 33.12417 3.50903, ... 33.781475 3.50903
0 POLYGON ((33.78148 3.50903, 33.12417 3.50903, ... 33.781475 3.50903
I tried also this approach:
def coord_lister(geom):
coords = list(geom.exterior.coords)
return (coords)
coordinates_list = df.geometry.apply(coord_lister)
But I got stuck on extracting the x,y coordinates.
Grateful for any insights.
CodePudding user response:
use apply() to do looping it is as simple as below
import pandas as pd
import geopandas as gpd
import shapely
import io
df = pd.read_csv(io.StringIO(""";id;add
0;028f342a-b26f-4e36-b5d1-25d3428cac2f;POLYGON ((33.781475 3.5090296, 33.1241675 3.5090296, 33.1241675 4.392868066666667, 33.781475 4.392868066666667, 33.781475 3.5090296))"""), sep=";")
# recreate geodataframe
gdf = gpd.GeoDataFrame(df, geometry=df["add"].apply(shapely.wkt.loads))
# expand the co-ordinates
gdf["geometry"].apply(lambda p: list(p.exterior.coords)).explode().apply(pd.Series).rename(columns=({0:"x", 1:"y"}))
| x | y | |
|---|---|---|
| 0 | 33.7815 | 3.50903 |
| 0 | 33.1242 | 3.50903 |
| 0 | 33.1242 | 4.39287 |
| 0 | 33.7815 | 4.39287 |
| 0 | 33.7815 | 3.50903 |
