AnsweredAssumed Answered

Seeking help with arcpy.Merge_management

Question asked by mcdo0007 on Mar 18, 2019
Latest reply on Mar 23, 2019 by mcdo0007

I am seeking a method to merge table outputs from ZonalHistogram (ZH) using a Python script. These files have a simple two-column format. E.g., AAA.dbf has two fields:

  • LABEL - the X-axis with values ranging from 0 to 100
  • AAA - the Y-axis counts produced by ZH

Similarly, BBB.dbf has two fields, LABEL and BBB, CCC.dbf has LABEL and CCC. I am able to plot these individual table files with arcpy graph, or render them in Excel.

 

I am trying to merge these files into a single output with the structure:
LABEL    AAA             BBB             CCC
0 - 100    ZH values    ZH values    ZH values

 

I started simply with:

 

tablesList = arcpy.ListTables()
arcpy.Merge_management(tablesList, "merged.dbf")

 

which gave me the four columns I was after but the output was arranged as:

 

rows 0 - 100:        LABEL (0 - 100)    ZH values        0                   0
rows 101 - 201:    LABEL (0 - 100)    0                      ZH values     0
rows 202 - 302:    Label (0 - 100)       0                      0                   ZH values

 

I have attempted to use field mapping as follows:

 

import arcpy
TESTDIR = <some dir>

arcpy.env.workspace = TESTDIR
arcpy.env.scratchWorkspace = TESTDIR
arcpy.env.overwriteOutput = True

tablesList = arcpy.ListTables()
inFields = [u'LABEL', u'AAA', u'BBB', u'CCC'] # Generated by arcpy.Describe()
fieldMappings = arcpy.FieldMappings()

# Deal with "LABEL" as special case (first field of first table)
fMap = arcpy.FieldMap()
fMap.addInputField(tablesList[0], inFields[0])
outField = fMap.outputField
outField.name = inFields[0]
fMap.outputField = outField
fieldMappings.addFieldMap(fMap)

# Add the second field of each file to the map
for i in range(len(tablesList)):
fMap = arcpy.FieldMap()
fMap.addInputField(tablesList[i], inFields[i + 1])
outField = fMap.outputField
outField.name = inFields[i + 1]
fMap.outputField = outField
fieldMappings.addFieldMap(fMap)
arcpy.Merge_management(tablesList, "merged.dbf", fieldMappings)

 

The output was the same. It seems I have merely replicated the built-in Merge_management. I would be most grateful for any advice on modifying the script to generate the merged output I am after.

Outcomes