AnsweredAssumed Answered

Reorder fields with python

Question asked by Suzanne on Oct 30, 2014
Latest reply on Oct 31, 2014 by Suzanne

I am creating a pivot table in python and have come across the scenario that when there are more than 9 pivot fields created that the order of the fields is technically out of order (e.g., pivotFld_1, pivotFld_10, pivotFld_11, pivotFld_2, pivotFld_3, pivotFld_4....).  I would like the order to be pivotFld_1, pivotFld_2, pivotFld_3, pivotFld_4....pivotFld_9,  pivotFld_10, pivotFld_11....

 

I have written the following code to reorder the fields but I am wondering if there is a better way to accomplish this?

 

testTbl = "path\\pivot table"

testTbl_vw = "testTbl_vw"

arcpy.MakeTableView_management(testTbl, testTbl_vw)

testFlds = list(f.name for f in arcpy.ListFields(testTbl_vw))

 

seqTest = []

for f in testFlds:

    if not f.find("pivotField_"):

        seqTest.append(f.lstrip("pivotField_"))

 

newFlds = []

for f in seqTest:

    if int(f) > 9:

        newFlds.append(f)

 

for f in newFlds:

    arcpy.AddField_management(testTbl_vw, "tmp_"+f, "LONG")

    arcpy.CalculateField_management(testTbl_vw, "tmp_"+f, "!pivotField_"+f+"!", "PYTHON")

    arcpy.DeleteField_management(testTbl_vw, "pivotField_"+f)

    arcpy.AddField_management(testTbl_vw, "pivotField_"+f, "LONG")

    arcpy.CalculateField_management(testTbl_vw, "pivotField_"+f, "!tmp_"+f+"!", "PYTHON")

    arcpy.DeleteField_management(testTbl_vw, "tmp_"+f)

Outcomes