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()
  • Which version of GeoPandas and Fiona you use ? – gene Nov 8 '16 at 7:42
  • I have the most recent versions of both installed. – wilbev Dec 4 '16 at 20:46
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)
  • 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 '17 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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