Select to view content in your preferred language

how to change the order of the fields of a table with arcpy

2850
2
05-31-2020 03:43 PM
RTMRTM
by
Emerging Contributor
I am automating a process with model builder.
I was looking in the toolbox for a tool that allows me to change the order of my fields.
But, I did not find anything
so
i'm looking for the option to do it with a script using arcpy.
could you help me with information about how to do it
0 Kudos
2 Replies
DanPatterson
MVP Esteemed Contributor

There is none.  You might have some success with

Make Table View—Data Management toolbox | Documentation 

but there is several caveats in the help topic which may make it difficult or impossible

If you ultimately need to make a new featureclass you can use FeatureclassToFeatureclass exporting only the object id field.  Then export the table to a numpy array (TableToNumPyArray), sort the fields there then use ExtendTable to join the sorted fields back to the newly created featureclass.


... sort of retired...
curtvprice
MVP Esteemed Contributor

Dan is correct, more on this:

ArcGIS should allow the ability to permanently reorder fields in a table

In arcpy the best way to do this is to create an arcpy FieldMappings object and use it with the Table to Table or Feature Class to Feature Class tool to make a new copy of the table with the order and field names you want. It's a little challenging but it does work. Going the numpy table route is Dan's go-to approach, I am less handy with numpy and pandas than he is. The numpy route is probably faster, but less scalable than using a field mapping inside the arcpy cocoon.

Note, I should say in ModelBuilder‌ you could create a field map using the Calculate Value tool, using an arcpy function to do the work of creating the field map, return the string representation and pass it to the tool that needs it.

This seems to be a common use case so I should write a blog post about it sometime.