-1

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?

EHB
  • 1,127
  • 3
  • 13
  • 24
  • I may be wrong, but it seems to me you are asking too many things at the same time. 1) [How to access an item in a tuple](https://stackoverflow.com/questions/3136059/getting-one-value-from-a-python-tuple); 2) [How to convert GeoJSON to a GeoPandas dataframe](https://stackoverflow.com/q/45552955/7851470); and 3) [How to write a GeoPandas dataframe to a shapefile](http://geopandas.org/io.html?highlight=shapefile#writing-spatial-data). I'm voting to close this question as "needing more focus". – Georgy Feb 02 '20 at 12:18

1 Answers1

1

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
realr
  • 3,652
  • 6
  • 23
  • 34