I'm having trouble converting a tuple containing the coordinates of polygon vertices to a shapefile.
Tuples are a very unfamiliar format to me; if it were in a dataframe, I could do it easily with geopandas.
shape= ({'type': 'Polygon',
'coordinates': [[(-148.7285301097261, 60.42704276401832),
(-148.7285301097261, 60.42693172262919),
(-148.7285856304207, 60.42693172262919),
(-148.72830802694787, 60.42704276401832),
(-148.7285301097261, 60.42704276401832)]]},
1.0)
I can't convert to dataframe via pd.DataFrame(shape)
; can't subset the tuple to access coordinates via shape['coordinates']
or pd.DataFrame(list(shape))
. I've reviewed this, and this, but am stuck on getting the coordinates out of the Tuple structure!
How can I create a shapefile (via Geopandas), given a tuple of the structure shown here?
You should be able to convert it to pandas DataFrame
by reading the first element of the tuple:
pd.DataFrame(shape[0]).explode('coordinates')
Out[1]:
type coordinates
0 Polygon (-148.7285301097261, 60.42704276401832)
0 Polygon (-148.7285301097261, 60.42693172262919)
0 Polygon (-148.7285856304207, 60.42693172262919)
0 Polygon (-148.72830802694787, 60.42704276401832)
0 Polygon (-148.7285301097261, 60.42704276401832)
If you need to split into x
and y
you can just take the items from the series:
df = pd.DataFrame(shape[0]).explode('coordinates').reset_index(drop=True)
df = df.join(df['coordinates'].apply(pd.Series)).rename(columns={0:'x', 1:'y'}).drop('coordinates', axis=1)
Out[2]:
type x y
0 Polygon -148.728530 60.427043
1 Polygon -148.728530 60.426932
2 Polygon -148.728586 60.426932
3 Polygon -148.728308 60.427043
4 Polygon -148.728530 60.427043