24

If I have a shapefile or geodatabase featureclass that has fields that I want to permanently reorder, is there a tool, script, or utility that will help me quickly accomplish this task?

Generally I know you have to create a new field, then populate it with the old values, then delete the old field. I am hoping there is something already created out there that will help with this.

Assuming you don't have FME or another ETL tool available, what is the next best suggestion?

This is NOT a view level change (ie- drag/drop the fields in order), but rather write out to a new shapefile or featureclass.

5
  • I find it hard to believe, but I can't find a way to do this. What's your use case for needing to re-order fields? Re-ordering fields on the fields tab of the layer properties in ArcMap isn't a solution? Commented Feb 7, 2011 at 20:16
  • 2
    The reordering of the fields is because the data will not be used in ArcMap, but with a less-sophisticated mapping software that 1) uses shapefiles and 2) does not allow for reordering on the client side and 3) the client needs to see the key attributes show up at the top of the "identify" tree. Commented Feb 7, 2011 at 20:32
  • Just edited my previously deleted answer. Hopefully you're not scared of the command line ;). Commented Feb 7, 2011 at 21:23
  • same question? gis.stackexchange.com/questions/5839/…
    – SaultDon
    Commented Feb 7, 2011 at 22:17
  • 2
    @SaultDon- this is not the same question. You referenced a question that wants to sort RECORDS (rows), but I want to sort FIELDS (columns). Commented Feb 7, 2011 at 23:01

15 Answers 15

15

I just confirmed that ogr2ogr can do this. Specify your field name order on the -select switch. For instance, if I have a shapefile with two fields, "Name" and "FolderPath" (in that order), but I want a new shapefile with "FolderPath" first I would do this:

C:\Temp>ogr2ogr -f "ESRI Shapefile" re_order_ogr.shp re_order1.shp -select "FolderPath,Name"
4
  • 2
    While it wasn't as user friendly an option as I had hoped for, it definitely does the trick. I have created an ArcGIS python script that helps build the inputs for it, and the user just has to include the -select "field1,field2,etc" option. You can download it at resources.arcgis.com/Resources2010/gallery/file/geoprocessing/… Commented Feb 8, 2011 at 18:45
  • I have a feature class on SDE with domains. Will this hold the associated domains?
    – MjonesGEO
    Commented Nov 5, 2014 at 16:52
  • @joebob no. AFAIK, ogr doesn't support datasets from SDE GDBs and it doesn't support domains either. Commented Nov 5, 2014 at 18:02
  • Thanks, I just used XRay and it can either reorder or replace fields while holding their domains in SDE.
    – MjonesGEO
    Commented Nov 5, 2014 at 18:34
6

The ET GeoWizards tool will do this, and it looks like the free version will do it without any limitations on the number of features.

1
  • It does but sadly doesn't retain aliases.
    – Howeitzer
    Commented Feb 16, 2016 at 12:33
6

The QGIS "Table Manager" Plugin now also has the ability to perform this task easily with no command line necessary.

6

In QGIS you can now use the processing toolbox (Ctl+Alt+T) and go to QGIS geoalgorithms > Vector table tools > Refactor fields.

From there you'll have all the tools to edit your table structure.

enter image description here

5

X-Ray arcmap add in have a tool for reorder fields of Geodatabes formatx-ray reorder fields tool here

1
  • This works very well. It will even hold your domains in fields if you're re-ordering an SDE. Great suggestion!!
    – MjonesGEO
    Commented Nov 5, 2014 at 17:59
4

Yo the best way to do it is to use Field Mappings. I've been struggling with this feature of ESRI software for years, but I'm finally content with this solution. Basically, you can just make a copy of your Feature Class with the fields permanently reordered using arcpy.FieldMappings. All of the data is carried over as well. Once the script is complete, just rename your old Feature Class to myFeatureClass_old, and your new one to myFeatureClass!

Here's the script, it's super straightforward:

import arcpy
'''
This is possible in python using FeatureClasstoFeatureClass with Fieldmappings. You can also rename fields at the same time.
So if you have a Feature Class with FIELD3, FIELD2, FIELD1 and you want the result to be FIELD1, FIELD2, FIELD3 then the following code should accomplish this.
'''
arcpy.env.workspace = r"C:\Users\myself\ArcData\my_geodatabase.gdb"
arcpy.env.overwriteOutput = True

input_fpath = "Lakes"

output_dpath = arcpy.env.workspace
output_fname = "Lakes_new"

fms = arcpy.FieldMappings()

fm = arcpy.FieldMap()
fm.addInputField(input_fpath,"FIELD1")
fms.addFieldMap(fm)

fm = arcpy.FieldMap()
fm.addInputField(input_fpath,"FIELD2")
fms.addFieldMap(fm)

fm = arcpy.FieldMap()
fm.addInputField(input_fpath,"FIELD3")
fms.addFieldMap(fm)

arcpy.conversion.FeatureClassToFeatureClass(input_fpath,output_dpath,output_fname,"",fms)
4

Feature Class to Feature Class now can perform this in 10.5 using the GP Tool Field Mapping section.

enter image description here

3

For the reference: MapInfo can also do it out-of-the-box. Just open the DBF and reorder the fields permanently. http://www.dbf-editor.com does it too ($40). Other DBF editors can probably do it too.

3
  • in this line, infolib should probably work too (convert to ascii (csv), rearrange to suit, re-convert back to info or dbf), as long as you're willing to live with the limitations of the .dbf file format. Commented Jun 9, 2011 at 22:11
  • You mean living with the limitations of the CSV format? DBF is the starting point for this question... Commented Jun 10, 2011 at 11:39
  • I meant dbf limits, thinking specifically that csv has no limits on field name length or record value lengths, and that starting point was file gdb, but re-reading the Q I see "shp" is mentioned in the title. So, limits all around ;-) Commented Jun 10, 2011 at 18:02
3

I have had a similar issue, and the fastest way to permanently reorder data fields, if you already have QGIS, is to use the 'Table Manager' plugin as previously suggested.

It is simple to install plugins and is user-friendly, as described on the page below:

http://www.qgistutorials.com/en/docs/using_plugins.html

It allows you to move the attributes in a specific order, rename the fields, insert any new fields and replicate them. It also allows you to save the original file, or rename it and save it differently from the original.

enter image description here

This was a quick and convenient solve to my attribute table management problem, and is highly recommended, especially for files with a large number of attributes associated with it.

2

Export the feature classes to an empty personal geodatabase (drag and drop is fastest), open the .mdb in Access, re-order the fields in Design View, save, then with ArcMap/Catalog copy back to shape or file geodatabase.

The same method works for renaming fields.

Be careful though, only work on copies, it is easy to screw everything up. (As Karey Jack notes in another answer, Esri discourages direct .mdb access). For safety ignore all the tables beginning with GDB_ and also those ending with _Shape_Index.

1

MakeQueryTable will let you define the order of your fields for a table or FC (Geodatabase only). The order that you specify the fields is the order of the output. I find this tool difficult to use. YMMV

Arctoolbox, data management tools, layers and table views, make query Table

1

Try OGR2OGR. You can pass an SQL query, and put the fields in the order you want them.

ogr2ogr outdataset indataset -sql "SELECT src_field1 AS dst_field1, src_field2 AS dst_field2 FROM sourcelayer"

Just tested this, and it works fine!

FYI, The easiest way to install OGR is via FWTools.

1

To reorder GIS fields that have like fields per feature class and table so those fields are reordered in front of all the rest of the fields. This works on the complete dataset. Make sure fields exist and are aliased properly.

Import Libraries

import arcpy
import sys

Declare Workspace

path="D:/temp"
dbname="/gis"
arcpy.env.workspace=path+dbname+'.gdb'
demogis=arcpy.env.workspace
newdb=path+dbname+'_New.gdb'
print(path+dbname+'.gdb')
print(demogis)
print (newdb)

Reorder Fields

Create New File Geodatabase and Feature Datasets

arcpy.management.Delete(path+dbname+'_New'+'.gdb')
arcpy.management.CreateFileGDB(path,dbname + '_New')
try:
    for ds in arcpy.ListDatasets():
        output_dpath = (path+dbname + '_New' + '.gdb')
        arcpy.CreateFeatureDataset_management(output_dpath, ds, ds)
except Exception:
    e = sys.exc_info()[1]
    print(e.args[0], ds)

Reorder Field Mapping in Feature Classes

'pfields' list needs to be updated to fields and alias field names in order. This will set order for the fields within the feature classes. Fields must exist in feature class.

pfields=[('AssetID','Asset Identifier'),('Display','Display Name'),('OpStatus','Operational Status'),('LifeCycleStatus','Lifecycle Status'),('Location','Location Description'),('Address','Address'),('OwnedBy','Owned By'),('MaintBy','Maintained By'),('PrimaryImage','Primary Image'),('CondInspScore','Condition Score'),('CondInspDate','Condition Date'),('WarrantyDate','Warranty Date'),('InstallDate','Install Date'),('InstallCost','Install Cost'),('ExpReplaceDate','Exp Replace Date'),('ExpReplaceCost','Exp Replace Cost'),('Age','Age'),('Criticality','Criticality'),('iPoF','Failure Probability'),('iCoF', 'Failure Consequence'),('iBRE','Business Risk'),('iMSPU','Maint Under Perform'),('iMSPO','Maint Over Perform'),('iMSR','Maint Score'),('iMCFY','Maint Curve Fast Yr'),('iMCSY','Maint Curve Slow Yr'),('iMCAY','Maint Curve Avg Yr'),('iMSName','Maint Strategy Name'),('iCalcDate','OpInsights Calc Date'),('IndFacID','Indoors Facility Identifier'),('IndLevID','Indoors Level Identifier'),('Comments','Comments')]
datasets = arcpy.ListDatasets(feature_type='feature')
datasets = [''] + datasets if datasets is not None else []
for ds in datasets:
    for fc in arcpy.ListFeatureClasses(feature_dataset=ds):
        pfield=[item[0] for item in pfields]
        palias=[item[1] for item in pfields]
        desc = arcpy.Describe(fc)
        output_dpath = (path+dbname + '_New' + '.gdb'+'/'+ds)
        input_fpath = demogis+'/'+ds+'/'+fc
        output_fname = fc
        fms = arcpy.FieldMappings()
        fcall = [(f.name,f.aliasName) for f in arcpy.ListFields(demogis+'/'+ds+'/'+fc) if f.editable]
        ffield = [item[0] for item in fcall]
        falias=[item[1] for item in fcall]
        fields2Add = list(set(fcall) - set(pfields))
        try:    
            for pfield,palias in pfields:
                fm = arcpy.FieldMap()
                fm.addInputField(input_fpath,pfield)
                of = fm.outputField
                of.name = pfield
                of.aliasName = palias
                fm.outputField = of
                fms.addFieldMap(fm)
        except Exception:
            e = sys.exc_info()[1]
            print(e.args[0], fc,pfield)
        try:
            for ffield,falias in fields2Add:
                if ffield != "SHAPE" and ffield != 'Shape':
                    fm = arcpy.FieldMap()
                    fm.addInputField(input_fpath,ffield)
                    of = fm.outputField
                    of.name = ffield
                    of.aliasName = falias
                    fm.outputField = of
                    fms.addFieldMap(fm)
        except Exception:
            e = sys.exc_info()[1]
            print(e.args[0], fc,ffield)
        arcpy.conversion.FeatureClassToFeatureClass(input_fpath,output_dpath,output_fname,"",field_mapping=fms)
    

Reorder Field Mapping in Tables

'pfields' list needs to be updated to fields and alias field names in order. This will set order for the fields within the tables. Fields must exist in tables.

pfields=[('AssetID','Asset Identifier'),('Display','Display Name'),('OpStatus','Operational Status'),('LifeCycleStatus','Lifecycle Status'),('Location','Location Description'),('Address','Address'),('OwnedBy','Owned By'),('MaintBy','Maintained By'),('PrimaryImage','Primary Image'),('CondInspScore','Condition Score'),('CondInspDate','Condition Date'),('WarrantyDate','Warranty Date'),('InstallDate','Install Date'),('InstallCost','Install Cost'),('ExpReplaceDate','Exp Replace Date'),('ExpReplaceCost','Exp Replace Cost'),('Age','Age'),('Criticality','Criticality'),('iPoF','Failure Probability'),('iCoF','Failure Consequence'),('iBRE','Business Risk'),('iMSPU','Maint Under Perform'),('iMSPO','Maint Over Perform'),('iMSR','Maint Score'),('iMCFY','Maint Curve Fast Yr'),('iMCSY','Maint Curve Slow Yr'),('iMCAY','Maint Curve Avg Yr'),('iMSName','Maint Strategy Name'),('iCalcDate','OpInsights Calc Date'),('IndFacID','Indoors Facility Identifier'),('IndLevID','Indoors Level Identifier'),('Comments','Comments')]
tables = arcpy.ListTables()
for tb in tables:
    output_dpath = (path+dbname + '_New' + '.gdb')
    input_fpath = demogis+'/'+tb
    pfield=[item[0] for item in pfields]
    palias=[item[1] for item in pfields]
    output_fname = tb
    fms = arcpy.FieldMappings()
    fcall = [(f.name,f.aliasName) for f in arcpy.ListFields(demogis+'/'+tb) if f.editable]
    ffield = [item[0] for item in fcall]
    falias=[item[1] for item in fcall]
    fields2Add = list(set(fcall) - set(pfields))
    try:    
        for pfield,palias in pfields:
            fm = arcpy.FieldMap()
            fm.addInputField(input_fpath,pfield)
            of = fm.outputField
            of.name = pfield
            of.aliasName = palias
            fm.outputField = of
            fms.addFieldMap(fm)
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0], tb,pfield)
    try:
        for ffield,falias in fields2Add:
            if ffield != "SHAPE" and ffield != 'Shape':
                fm = arcpy.FieldMap()
                fm.addInputField(input_fpath,ffield)
                of = fm.outputField
                of.name = ffield
                of.aliasName = falias
                fm.outputField = of
                fms.addFieldMap(fm)
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0], tb,ffield)
    arcpy.conversion.TableToTable(input_fpath,output_dpath,output_fname,"",field_mapping=fms)
0

Open the .mdb file in MS Access and reorder the fields using drag and drop in 'Design View'

Though ESRI discourages editing a database in Access ESRI link

1
  • 2
    Welcome to our site, Karey! Isn't this the same answer Matt Wilkie gave in this thread 18 months ago (gis.stackexchange.com/a/5879)?
    – whuber
    Commented Jul 30, 2012 at 13:28
0

No one has mentioned the ESRI Geodatabase Diagrammer.

A resource provided by ESRI for editing the XML structure of your geodatabase and files. As far as I'm concerned it's essential if you're working on anything where design has to be perfect (long term project). It'll keep you from having to re-create files continually after making a simple mistake.

1
  • 1
    Did you see the comment (to the question itself) stating that this was not a database reorganization, but rather is needed to export the data?
    – whuber
    Commented Jul 30, 2012 at 13:29

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