Search code examples
pandasdataframesortinggisgeopandas

Sorting/ordering geometry column by longitude in Geopandas dataframe


I have a bunch of POINT Z (x,y,z) values in a Geopandas geometry column. I want to take these points and construct a LINE which in turn I can buffer to create a POLYGON.

To generate the line I use:

lineStringObj = LineString([[a.x, a.y] for a in gdf.geometry.values])

Which is fine when all the point values are nicely ordered North/South in latitude. However, my dataframe needs to be ordered East/West in longitude so when I create my linestringobj the points join in a nice straight line rather than zigzagging based on the latitude order. How can I sort/re-order my dataframe base on the longitude (gdf.geometry.values.x) value of the geometry column?

enter image description here


Solution

  • You can use pd.Series.argsort to get the sort order:

    gdf = gdf.iloc[
       gdf.geometry.x.argsort().values
    ]
    

    At this point you can construct your linestring with the same code you have above.