3

I have a shapefile I'm reading in using GeoPandas and then I do some geometry conversion of the data but in the process it unfortunately sorts the columns alphabetically. I need to preserve original order of the columns which has over 200 columns.

Here is the start of the code I'm using. I imagine I have to somehow store the original column order and apply it to the GeoPandas dataframe.

import geopandas as gpd


shpfile = r"C:\data\myfile.shp"
poly = gpd.read_file(shpfile)
poly.head()
2
  • Which version of GeoPandas and Fiona you use ?
    – gene
    Nov 8, 2016 at 7:42
  • I have the most recent versions of both installed.
    – wilbev
    Dec 4, 2016 at 20:46

3 Answers 3

1

If you just need a variable that stores the index at the end of those 4 lines for later use and then uses that to sort the dataframe down the line, then how about:

poly['stored_index'] = poly.index
...
poly.sort_values('stored_index', inplace=True)
1
  • Sorry for the slow reply. I've tried your suggestion here but it doesn't seem to help I believe since the geopandas read seems to change the order of the columns so I need to get the order before that I believe. So tried creating a dataframe from a dbf file and user our same code but I keep getting Type Error on the sort_values function. Any other help would be appreciated.
    – wilbev
    Jan 3, 2017 at 0:56
0

store the column order right after read-in...

import geopandas as gpd

shpfile = r"C:\data\myfile.shp"
poly = gpd.read_file(shpfile)
cols = poly.columns
# ...do something that will change the order of the poly GDF...
# ...then, as long as your work hasn't created any new columns...
poly = poly[cols]

if you add new columns do..

cols = poly.columns.tolist()

and then manipulate the new column/s into that list where you want them in the GDF.

0

What version of geopandas are you using? I found that when I read in a shapefile with v0.6.1, the column order was somewhat alphabetized without any command from my script to do so. When I ran the exact same code with the same version of pandas (v1.3.5) and geopandas upgraded to v0.13.2, the resulting dataset (in GeoJSON format) had the original column order from the input .shp preserved. I'm not sure what changed between these versions or when it changed (maybe v0.11?), but I'd recommend setting specific requirements for more recent versions of geopandas to fix this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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