Skip to content

Instantly share code, notes, and snippets.

@pyRobShrk
Last active March 21, 2018 17:05
Show Gist options
  • Select an option

  • Save pyRobShrk/c766b08c13bc76c590c18026f2ccf10b to your computer and use it in GitHub Desktop.

Select an option

Save pyRobShrk/c766b08c13bc76c590c18026f2ccf10b to your computer and use it in GitHub Desktop.
ArcMap script to copy a shapefile into a new smaller shapefile (in memory)
# Compress Shapefile by reducing Text Field lengths, dropping M and Z
# Unfortunately .management.AlterField only works for unpopulated text fields
# Process: Copy Table to NumPy array, Determine max length of text fields
# Create blank feature with previous as template, alter text field length
# Copy features to new feature class in memory
import arcpy.management as mg
import numpy as np
def compressSHP(inSHP, outSHP):
fields = [f.name for f in arcpy.ListFields(inSHP) if not f.name == 'Shape']
fields.insert(0,'SHAPE@')
txtFields = [f.name for f in arcpy.ListFields(inSHP,field_type="String")]
maxLens = np.array([0]*len(txtFields))
for r in arcpy.da.SearchCursor(inSHP,txtFields):
l = np.array([len(a) for a in r])
maxLens = np.maximum(maxLens,l)
meta = arcpy.Describe(inSHP)
outSHP = mg.CreateFeatureclass("in_memory",outSHP,meta.shapeType,inSHP,
"DISABLED","DISABLED",meta.spatialReference)
for txt, l in zip(txtFields, maxLens):
mg.AlterField(outSHP,txt,field_length=l)
ins = arcpy.InsertCursor(outSHP,fields)
for rw in arcpy.SearchCursor(inSHP,fields):
ins.insertRow(rw)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment