Last active
March 21, 2018 17:05
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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