### Verify ArcPy Installation Source: https://github.com/esri/arcpy/blob/main/_autodocs/quick-start-guide.md Import ArcPy and print the ArcGIS Pro version to confirm successful installation and accessibility. ```python import arcpy # Verify installation print(f"ArcGIS Version: {arcpy.GetInstallInfo()['Version']}") ``` -------------------------------- ### Basic Buffer Script Tool Example Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md A complete ArcPy script tool that performs a buffer operation on an input feature class. It demonstrates how to get parameters, validate inputs, execute a geoprocessing tool, and provide messages. ```python import arcpy import os def main(): """Main tool function.""" try: # Get parameters input_fc = arcpy.GetParameterAsText(0) output_fc = arcpy.GetParameterAsText(1) distance = arcpy.GetParameterAsText(2) dissolve = arcpy.GetParameter(3) # Boolean # Validate inputs if not arcpy.Exists(input_fc): arcpy.AddError(f"Input not found: {input_fc}") return arcpy.AddMessage(f"Buffering {input_fc}...") # Set environment arcpy.env.overwriteOutput = True # Execute buffer if dissolve: arcpy.analysis.Buffer( input_fc, output_fc, distance, dissolve_option="ALL" ) arcpy.AddMessage("Applied dissolve option") else: arcpy.analysis.Buffer(input_fc, output_fc, distance) arcpy.AddMessage(f"Successfully created: {output_fc}") # Set output parameter arcpy.SetParameter(1, output_fc) except arcpy.ExecuteError: arcpy.AddError(f"ArcGIS Error: {arcpy.GetMessages()}") except Exception as e: arcpy.AddError(f"Unexpected Error: {e}") if __name__ == "__main__": main() ``` -------------------------------- ### ArcPy SpatialReference Constructor Examples Source: https://github.com/esri/arcpy/blob/main/_autodocs/arcpy-core-modules.md Shows how to create SpatialReference objects using WKID, a .prj file, or Well-Known Text. Imports are required. ```python import arcpy # WGS84 (EPSG:4326) sr_wgs84 = arcpy.SpatialReference(4326) # Web Mercator (EPSG:3857) sr_webmerc = arcpy.SpatialReference(3857) # From projection file sr_custom = arcpy.SpatialReference("C:/projections/custom.prj") # Create feature class with spatial reference arcpy.management.CreateFeatureclass( "C:/data", "points.shp", "POINT", spatial_reference=sr_wgs84 ) ``` -------------------------------- ### Spatial Reference Usage Examples Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Demonstrates creating SpatialReference objects from WKID and projection files, and using them in feature class creation and tool operations. ```python import arcpy # Create from WKID (WGS84) sr_wgs84 = arcpy.SpatialReference(4326) print(f"Name: {sr_wgs84.name}") print(f"Factory Code: {sr_wgs84.factoryCode}") print(f"Is Projected: {sr_wgs84.isProjected}") # Create from projection file sr_custom = arcpy.SpatialReference() sr_custom.createFromFile("C:/projections/state_plane.prj") # Use in feature class creation arcpy.management.CreateFeatureclass( "C:/gdb.gdb", "points_wgs84", "POINT", spatial_reference=sr_wgs84 ) # Use in tool operations arcpy.analysis.Buffer( "C:/data/input.shp", "C:/data/output.shp", "100 Meters", method="GEODESIC" ) arcpy.env.outputCoordinateSystem = sr_wgs84 ``` -------------------------------- ### ArcPy Analysis Buffer Usage Examples Source: https://github.com/esri/arcpy/blob/main/_autodocs/arcpy-core-modules.md Demonstrates buffering features by a fixed distance and by a field value. Ensure necessary imports are present. ```python import arcpy # Buffer by fixed distance arcpy.analysis.Buffer( "C:/data/roads.shp", "C:/output/road_buffer_100ft.shp", "100 Feet", dissolve_option="ALL" ) # Buffer by field arcpy.analysis.Buffer( "C:/data/facilities.shp", "C:/output/facility_buffers.shp", "BUFFER_DISTANCE_METERS" ) ``` -------------------------------- ### Create Feature Class with Spatial Index Optimization Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Use this example to create a polyline feature class with optimized spatial indexing by specifying spatial grid sizes for improved performance. ```Python import arcpy # Create with spatial index optimization arcpy.management.CreateFeatureclass( "C:/gdb.gdb", "indexed_roads", "POLYLINE", spatial_grid_1=1000, spatial_grid_2=10000 ) ``` -------------------------------- ### ArcPy Environment Settings Examples Source: https://github.com/esri/arcpy/blob/main/_autodocs/arcpy-core-modules.md Illustrates setting global geoprocessing environment variables like workspace, output coordinate system, and overwrite behavior. Requires arcpy import. ```python import arcpy # Set workspace arcpy.env.workspace = "C:/data" # Set output coordinate system arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(4326) # Enable output overwriting arcpy.env.overwriteOutput = True # Set extent to specific feature class arcpy.env.extent = "C:/data/study_area.shp" ``` -------------------------------- ### Create Dependent Parameters Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Sets up parameter dependencies where one parameter's availability or value depends on another. This example populates a field name parameter based on an input feature class. ```python import arcpy # Script that validates parameter dependencies input_fc = arcpy.GetParameterAsText(0) field_name = arcpy.GetParameterAsText(1) # Get list of available fields if input_fc and arcpy.Exists(input_fc): desc = arcpy.Describe(input_fc) field_names = [f.name for f in desc.fields] arcpy.SetParameterAsText(1, ";".join(field_names)) ``` -------------------------------- ### Get Tool Parameters by Index Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Retrieve tool parameters by their positional index. This is useful for accessing inputs like feature classes and distances. ```python import arcpy # Get tool parameters by index input_fc = arcpy.GetParameter(0) output_fc = arcpy.GetParameter(1) distance = arcpy.GetParameter(2) ``` -------------------------------- ### Create Polygon Feature Class with Z Values Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md This example demonstrates creating a polygon feature class that includes Z (elevation) values, suitable for 3D data, with a specified spatial reference. ```Python import arcpy # Create polygon feature class with Z values arcpy.management.CreateFeatureclass( "C:/gdb.gdb", "parcels_3d", "POLYGON", has_z=True, spatial_reference=arcpy.SpatialReference(32610) ) ``` -------------------------------- ### Get Tool Parameters with Multiple Types Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Demonstrates retrieving various parameter types (feature class, double, field, boolean) from a tool dialog. Conditional logic can be applied based on parameter values. ```python import arcpy # Tool with multiple parameter types input_fc = arcpy.GetParameter(0) # Feature class output_fc = arcpy.GetParameter(1) # Feature class distance = arcpy.GetParameter(2) # Double field_name = arcpy.GetParameter(3) # Field calculate = arcpy.GetParameter(4) # Boolean if calculate: print(f"Processing {input_fc} with field {field_name}") ``` -------------------------------- ### Create Custom Error Log with ArcPy Buffer Source: https://github.com/esri/arcpy/blob/main/_autodocs/error-handling.md This Python snippet demonstrates how to set up basic logging to a file and use it within a function that performs an ArcPy Buffer operation. It logs the start, success, warnings, and failures of the buffer process. ```python import arcpy import logging # Setup logging logging.basicConfig( filename="arcpy_operations.log", level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) def logged_buffer(input_fc, output_fc, distance): """Buffer with logging.""" try: logging.info(f"Starting buffer: {input_fc} -> {output_fc}") result = arcpy.analysis.Buffer(input_fc, output_fc, distance) if result.severity == 0: logging.info("Buffer completed successfully") else: logging.warning(f"Buffer completed with warnings: {arcpy.GetMessages()}") return True except Exception as e: logging.error(f"Buffer failed: {e}") logging.error(f"Messages: {arcpy.GetMessages()}") return False # Usage logged_buffer("input.shp", "output.shp", "100 Meters") ``` -------------------------------- ### Update Field Values with UpdateCursor Source: https://github.com/esri/arcpy/blob/main/_autodocs/data-access-cursors.md Example of updating specific field values in a feature class. Ensure the feature class path and field names are correct. ```python import arcpy fc = "C:/gdb.gdb/buildings" # Update field values with arcpy.da.UpdateCursor(fc, ["SQUARE_FOOTAGE", "PRICE_PER_SF"]) as cursor: for row in cursor: sqft = row[0] if sqft and sqft > 0: row[1] = 250.00 * sqft # Calculate price cursor.updateRow(row) ``` -------------------------------- ### Get Parameters as Text Strings Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Retrieve all tool parameters as their string representation using arcpy.GetParameterAsText(). This requires explicit conversion for non-string types like doubles. ```python import arcpy # Get parameters as text strings input_fc = arcpy.GetParameterAsText(0) distance_str = arcpy.GetParameterAsText(1) # Convert as needed distance = float(distance_str) ``` -------------------------------- ### Get Feature Class Extent and Set Environment Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Shows how to obtain the extent of a feature class using arcpy.Describe and set the analysis extent using the retrieved extent object. ```python import arcpy fc = "C:/gdb.gdb/buildings" desc = arcpy.Describe(fc) extent = desc.extent print(f"Extent: {extent.XMin}, {extent.YMin}, {extent.XMax}, {extent.YMax}") # Use extent for analysis arcpy.env.extent = extent ``` -------------------------------- ### Initialize ArcPy Environment with Specific Settings Source: https://github.com/esri/arcpy/blob/main/_autodocs/environment-settings.md A function to initialize key ArcPy environment settings such as workspace, scratch workspace, overwrite output, and output coordinate system. It also includes a check to ensure the specified workspace exists and prints the initialized settings. This is useful for setting up a consistent processing environment at the start of a script or tool. ```python import arcpy import os def initialize_environment(workspace_path, scratch_path): """Initialize ArcPy environment for processing.""" arcpy.env.workspace = workspace_path arcpy.env.scratchWorkspace = scratch_path arcpy.env.overwriteOutput = True arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(4326) # Verify workspace exists if not os.path.exists(workspace_path): raise ValueError(f"Workspace not found: {workspace_path}") print(f"Environment initialized:") print(f" Workspace: {arcpy.env.workspace}") print(f" Scratch: {arcpy.env.scratchWorkspace}") print(f" Output CRS: {arcpy.env.outputCoordinateSystem.name}") # Usage initialize_environment("C:/data", "C:/temp/scratch.gdb") ``` -------------------------------- ### Calculating Field Values Based on Geometry Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Demonstrates calculating field values in a feature class using arcpy.management.CalculateField. This example shows how to calculate area using '!SHAPE.AREA!' and a custom formula for price per square foot. ```python import arcpy fc = "C:/gdb.gdb/buildings" # Calculate geometry-based field arcpy.management.CalculateField( fc, "SQUARE_FOOTAGE", "!SHAPE.AREA!", expression_type="PYTHON3" ) # Calculate with formula arcpy.management.CalculateField( fc, "PRICE_PER_SF", "!TOTAL_PRICE! / !SQUARE_FOOTAGE!", expression_type="PYTHON3" ) ``` -------------------------------- ### Create and Access Point Geometry Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Demonstrates how to create a Point geometry object with a spatial reference and access its X and Y coordinates. Also shows creating a Point with a Z value. ```python import arcpy # Create a point point = arcpy.geometry.Point( -118.2437, 34.0522, spatial_reference=arcpy.SpatialReference(4326) ) # Access coordinates print(f"X: {point.X}, Y: {point.Y}") # With Z value point_3d = arcpy.geometry.Point(-118.2437, 34.0522, 100.5) print(f"Z: {point_3d.Z}") ``` -------------------------------- ### Check Installed Python and Package Versions Source: https://github.com/esri/arcpy/blob/main/_autodocs/python-distributions.md Use this script to determine the ArcGIS Pro version, Python version, and specific package versions like NumPy installed within your ArcGIS Pro environment. ```python import arcpy import sys # Get ArcGIS Pro version pro_version = arcpy.GetInstallInfo()["Version"] print(f"ArcGIS Pro version: {pro_version}") # Get Python version print(f"Python version: {sys.version}") # Check for specific packages try: import numpy print(f"NumPy version: {numpy.__version__}") except ImportError: print("NumPy not installed") ``` -------------------------------- ### Create Folder with CreateFolder_management() Source: https://github.com/esri/arcpy/blob/main/_autodocs/common-utilities.md CreateFolder_management() creates a new directory at the specified path. The function returns the path to the newly created folder. ```python import arcpy # Create folder arcpy.CreateFolder_management("C:/data", "analysis") # Result: C:/data/analysis/ ``` -------------------------------- ### getDefinitionQuery() Source: https://github.com/esri/arcpy/blob/main/_autodocs/map-layer-objects.md Gets the current where clause applied to the layer. ```APIDOC ## getDefinitionQuery() ### Description Gets the current where clause applied to the layer. ### Method `layer.getDefinitionQuery()` ### Returns - **where_clause** (str) - The current SQL where clause. ### Usage Example ```python import arcpy project = arcpy.mp.ArcGISProject("C:/projects/my_project.aprx") map_obj = project.listMaps("Map")[0] for layer in map_obj.listLayers("Buildings"): query = layer.getDefinitionQuery() print(f"Definition Query: {query}") ``` ``` -------------------------------- ### Get Tool Messages Source: https://github.com/esri/arcpy/blob/main/_autodocs/error-handling.md Retrieve and print messages from a geoprocessing tool execution, including severity and individual messages. ```Python import arcpy # Execute tool result = arcpy.analysis.Buffer("input.shp", "output.shp", "100 Meters") # Get messages print(f"Severity: {result.severity}") print(f"Message Count: {result.messageCount}") # Iterate through messages for i in range(result.messageCount): print(f"Message {i}: {result.getMessage(i)}") # Print all messages print(result.getMessages()) ``` -------------------------------- ### Create and Access Extent Properties Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Demonstrates how to create an Extent object with specified coordinates and access its properties like minimum/maximum X and Y values, width, and height. ```python import arcpy # Create extent extent = arcpy.Extent(-118.25, 34.05, -118.24, 34.06) # Access extent properties print(f"Min X: {extent.XMin}") print(f"Min Y: {extent.YMin}") print(f"Max X: {extent.XMax}") print(f"Max Y: {extent.YMax}") print(f"Width: {extent.width}") print(f"Height: {extent.height}") ``` -------------------------------- ### Describe Table Properties Source: https://github.com/esri/arcpy/blob/main/_autodocs/describe-objects.md Use arcpy.Describe to get properties of a table. This is useful for understanding the structure and record count of a table. ```Python import arcpy table = "C:/gdb.gdb/building_data" desc = arcpy.Describe(table) # Get table properties print(f"Name: {desc.name}") print(f"Row Count: {desc.rowCount}") print(f"Field Count: {desc.fieldCount}") # Get field names field_names = [f.name for f in desc.fields] print(f"Fields: {field_names}") ``` -------------------------------- ### Update Geometry with UpdateCursor Source: https://github.com/esri/arcpy/blob/main/_autodocs/data-access-cursors.md Example of updating the geometry of features using UpdateCursor. This involves accessing and modifying the SHAPE@ token. ```python import arcpy fc = "C:/gdb.gdb/buildings" # Update geometry with arcpy.da.UpdateCursor(fc, ["BUILDING_ID", "SHAPE@"]) as cursor: for row in cursor: geom = row[1] # Process geometry buffered = geom.buffer(100) row[1] = buffered cursor.updateRow(row) ``` -------------------------------- ### Working with Multi-band Rasters in ArcPy Source: https://github.com/esri/arcpy/blob/main/_autodocs/raster-analysis.md Demonstrates loading a multi-band raster, extracting individual bands, and calculating NDVI. Ensure the Spatial Analyst extension is checked out before running. ```python import arcpy from arcpy.sa import * arcpy.CheckOutExtension("Spatial") # Load multi-band raster landsat = Raster("C:/rasters/landsat_bands.tif") # Extract individual bands band1 = landsat[0] # First band band2 = landsat[1] # Second band band3 = landsat[2] # Third band # Calculate NDVI (Normalized Difference Vegetation Index) # NDVI = (NIR - Red) / (NIR + Red) nir = landsat[3] red = landsat[2] ndvi = (nir - red) / (nir + red) ndvi.save("C:/output/ndvi.tif") ``` -------------------------------- ### Accessing Central Meridian Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Get the central meridian longitude for a spatial reference. This parameter is typically 0 for most geographic coordinate systems. ```python sr = arcpy.SpatialReference(4326) cm = sr.centralMeridian # Usually 0 for geographic systems ``` -------------------------------- ### Perform Suitability Analysis Source: https://github.com/esri/arcpy/blob/main/_autodocs/raster-analysis.md Create a suitability map by classifying multiple raster criteria (e.g., elevation, slope, vegetation) and combining them. Areas meeting all specified conditions are identified. ```python import arcpy from arcpy.sa import * arcpy.CheckOutExtension("Spatial") # Load input rasters elevation = Raster("C:/rasters/elevation.tif") slope = Raster("C:/rasters/slope.tif") vegetation = Raster("C:/rasters/vegetation.tif") # Classify each criterion elevation_suitable = Con((elevation > 100) & (elevation < 2000), 1, 0) slope_suitable = Con(slope < 30, 1, 0) vegetation_suitable = Con((vegetation > 0.5), 1, 0) # Combine criteria (all must be suitable) suitability = elevation_suitable + slope_suitable + vegetation_suitable # Areas with all criteria met (value = 3) final = Con(suitability == 3, 1, 0) final.save("C:/output/suitable_areas.tif") ``` -------------------------------- ### Describe Layer Properties Source: https://github.com/esri/arcpy/blob/main/_autodocs/describe-objects.md Use arcpy.Describe to get properties of a layer object from a map. This is useful for inspecting layer details programmatically. ```python import arcpy # Describe layer from map project = arcpy.mp.ArcGISProject("C:/projects/my_project.aprx") map_obj = project.listMaps("Map")[0] for layer in map_obj.listLayers(): desc = arcpy.Describe(layer) print(f"Layer: {desc.name}") print(f"Type: {desc.dataType}") print(f"Data Source: {desc.dataSource}") ``` -------------------------------- ### Describe Raster Properties Source: https://github.com/esri/arcpy/blob/main/_autodocs/describe-objects.md Use arcpy.Describe to get properties of a raster dataset. This is useful for understanding the spatial and pixel characteristics of a raster. ```Python import arcpy raster = "C:/rasters/elevation.tif" desc = arcpy.Describe(raster) # Get raster properties print(f"Pixel Type: {desc.pixelType}") print(f"Bands: {desc.bandCount}") print(f"Dimensions: {desc.columnCount} x {desc.rowCount}") print(f"Cell Size: {desc.cellSize}") print(f"Extent: {desc.extent}") print(f"No Data Value: {desc.noDataValue}") ``` -------------------------------- ### Get Layer Definition Query Source: https://github.com/esri/arcpy/blob/main/_autodocs/map-layer-objects.md Retrieves the current definition query (where clause) applied to a layer. This is useful for inspecting or logging filter settings. ```Python import arcpy project = arcpy.mp.ArcGISProject("C:/projects/my_project.aprx") map_obj = project.listMaps("Map")[0] for layer in map_obj.listLayers("Buildings"): query = layer.getDefinitionQuery() print(f"Definition Query: {query}") ``` -------------------------------- ### Perform Buffer Analysis Source: https://github.com/esri/arcpy/blob/main/_autodocs/quick-start-guide.md Creates buffer zones around input features. Specify the input features, output buffer feature class, and buffer distance. ```python import arcpy # Create buffer zones arcpy.analysis.Buffer( "C:/data/roads.shp", "C:/output/road_buffer.shp", "100 Meters" ) ``` -------------------------------- ### Get All Messages from Tool Execution Source: https://github.com/esri/arcpy/blob/main/_autodocs/error-handling.md Retrieves all messages, including errors and warnings, from the last executed geoprocessing tool. Useful for comprehensive logging. ```python import arcpy arcpy.analysis.Buffer("input.shp", "output.shp", "100 Meters") # Get all messages all_messages = arcpy.GetMessages() print(all_messages) # Get errors only (severity 2) errors = arcpy.GetMessages(2) print(errors) # Get warnings only (severity 1) warnings = arcpy.GetMessages(1) print(warnings) ``` -------------------------------- ### CreateFolder_management() Source: https://github.com/esri/arcpy/blob/main/_autodocs/common-utilities.md Creates a new folder at the specified path with the given name. ```APIDOC ## CreateFolder_management() ### Description Creates a new folder. ### Parameters #### Path Parameters - **out_folder_path** (string) - Required - The path where the new folder will be created. - **out_name** (string) - Required - The name of the new folder to create. ### Request Example ```python import arcpy # Create folder arcpy.CreateFolder_management("C:/data", "analysis") # Result: C:/data/analysis/ ``` ``` -------------------------------- ### Get Specific Error Messages Source: https://github.com/esri/arcpy/blob/main/_autodocs/error-handling.md Catch an ArcPy ExecuteError and retrieve only the error messages (severity level 2) using arcpy.GetMessages(2). ```Python import arcpy try: result = arcpy.management.Buffer( "nonexistent.shp", "output.shp", "100 Meters" ) except arcpy.ExecuteError as e: # Get error messages error_messages = arcpy.GetMessages(2) # 2 = errors only print(f"Error: {error_messages}") ``` -------------------------------- ### Context-Specific Environment Management with try-finally Source: https://github.com/esri/arcpy/blob/main/_autodocs/environment-settings.md Provides a robust method for managing environment settings within a specific function or block of code. It saves the original environment settings, applies custom settings for the operation, and then guarantees the restoration of the original settings using a try-finally block, even if errors occur during processing. ```python import arcpy def process_with_custom_env(input_fc, output_fc): # Save current environment original_workspace = arcpy.env.workspace original_sr = arcpy.env.outputCoordinateSystem original_extent = arcpy.env.extent try: # Set custom environment for this operation arcpy.env.workspace = "C:/temp/processing" arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(3857) # Perform operations arcpy.analysis.Buffer(input_fc, output_fc, "100 Meters") finally: # Restore original environment arcpy.env.workspace = original_workspace arcpy.env.outputCoordinateSystem = original_sr arcpy.env.extent = original_extent ``` -------------------------------- ### Prepare Tool for Publication Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Create a tool that is ready for publication to ArcGIS Server by using absolute paths or registered data sources and handling potential errors. ```python import arcpy def create_publishable_tool(): """Tool prepared for publishing to ArcGIS Server.""" try: # Get parameters input_fc = arcpy.GetParameterAsText(0) output_fc = arcpy.GetParameterAsText(1) # Validate all inputs if not arcpy.Exists(input_fc): arcpy.AddError(f"Input required: {input_fc}") return # Use absolute paths or registered data sources arcpy.env.workspace = "C:/data" arcpy.env.overwriteOutput = True # Execute operation arcpy.analysis.Buffer(input_fc, output_fc, "100 Meters") # Provide clear output arcpy.AddMessage(f"Output created: {output_fc}") arcpy.SetParameter(1, output_fc) except Exception as e: arcpy.AddError(f"Tool failed: {e}") arcpy.AddMessage(arcpy.GetMessages()) if __name__ == "__main__": create_publishable_tool() ``` -------------------------------- ### Retrieving Spatial Reference Domain Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Get the geographic bounds (domain) of a spatial reference. The domain is returned as a tuple of (minX, minY, maxX, maxY). ```python sr = arcpy.SpatialReference(4326) domain = sr.domain # Returns (minX, minY, maxX, maxY) # For WGS84: (-180, -90, 180, 90) ``` -------------------------------- ### Automate Map Creation with ArcPy Source: https://github.com/esri/arcpy/blob/main/_autodocs/quick-start-guide.md Use this snippet to open an existing ArcGIS project, add layers to a map, apply definition queries, and save the project. ```python import arcpy # Open project project = arcpy.mp.ArcGISProject("C:/projects/my_project.aprx") # Get map map_obj = project.listMaps("Map")[0] # Add layer layer_file = arcpy.mp.LayerFile("C:/layers/buildings.lyrx") map_obj.addLayer(layer_file, "BOTTOM") # Apply filter for layer in map_obj.listLayers("Buildings"): layer.setDefinitionQuery("SQUARE_FOOTAGE > 5000") # Save project project.save() ``` -------------------------------- ### Access True Centroid with SHAPE@TRUECENTROID Source: https://github.com/esri/arcpy/blob/main/_autodocs/data-access-cursors.md Get the true centroid coordinates of a feature using the SHAPE@TRUECENTROID token. This returns a tuple of (X, Y) coordinates. ```python with arcpy.da.SearchCursor(fc, ["BUILDING_ID", "SHAPE@TRUECENTROID"]) as cursor: for row in cursor: cx, cy = row[1] print(f"{row[0]} center: ({cx}, {cy})") ``` -------------------------------- ### Geometry Class Constructors Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Illustrates the basic constructor signatures for creating Point, Polyline, Polygon, and Multipoint geometry objects in ArcPy. ```python arcpy.geometry.Point(x, y, z=None, m=None, spatial_reference=None) arcpy.geometry.Polyline(array, spatial_reference=None) arcpy.geometry.Polygon(array, spatial_reference=None) arcpy.geometry.Multipoint(array, spatial_reference=None) ``` -------------------------------- ### Accessing Scale Factor at Origin Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Get the scale factor at the origin for a spatial reference. This value is typically 0.9996 for Universal Transverse Mercator (UTM) systems. ```python sr = arcpy.SpatialReference(32610) scale = sr.scaleAtOrigin # Typically 0.9996 for UTM ``` -------------------------------- ### Save and Restore ArcPy Environments Source: https://github.com/esri/arcpy/blob/main/_autodocs/environment-settings.md Demonstrates how to save the current state of specific environment settings (workspace, outputCoordinateSystem, extent, overwriteOutput) into a dictionary and then restore them after modifying them. This is crucial for ensuring that changes to environments are localized and do not affect subsequent operations. ```python import arcpy # Save current environments saved_env = { 'workspace': arcpy.env.workspace, 'outputCoordinateSystem': arcpy.env.outputCoordinateSystem, 'extent': arcpy.env.extent, 'overwriteOutput': arcpy.env.overwriteOutput } # Modify environment arcpy.env.workspace = "C:/temp" # Restore saved environments arcpy.env.workspace = saved_env['workspace'] arcpy.env.outputCoordinateSystem = saved_env['outputCoordinateSystem'] arcpy.env.extent = saved_env['extent'] arcpy.env.overwriteOutput = saved_env['overwriteOutput'] ``` -------------------------------- ### SearchCursor Usage: Simple Read Source: https://github.com/esri/arcpy/blob/main/_autodocs/data-access-cursors.md Demonstrates a basic SearchCursor to iterate through records and access fields by index. Ensure the 'arcpy' module is imported. ```python import arcpy fc = "C:/gdb.gdb/buildings" # Simple search with arcpy.da.SearchCursor(fc, ["OID@", "BUILDING_ID", "SHAPE@"]) as cursor: for row in cursor: oid = row[0] bid = row[1] geometry = row[2] print(f"OID: {oid}, ID: {bid}, Area: {geometry.area}") ``` -------------------------------- ### Create Polygon Geometry Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Demonstrates the creation of a Polygon geometry object using an array of Point objects, ensuring the ring is closed by repeating the first vertex. ```python import arcpy # Create vertices for polygon vertices = [ arcpy.geometry.Point(-118.2437, 34.0522), arcpy.geometry.Point(-118.2432, 34.0525), arcpy.geometry.Point(-118.2425, 34.0520), arcpy.geometry.Point(-118.2437, 34.0522) # Close ring ] # Create array of points array = arcpy.Array(vertices) # Create polygon polygon = arcpy.geometry.Polygon( array, spatial_reference=arcpy.SpatialReference(4326) ) ``` -------------------------------- ### Detect Spatial Reference from Feature Class Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Use arcpy.Describe to get the spatial reference of an existing feature class. This is useful for understanding the coordinate system of your input data. ```python import arcpy # Detect spatial reference from existing data fc = "C:/data/parcels.shp" sr = arcpy.Describe(fc).spatialReference print(f"Coordinate System: {sr.name}") print(f"EPSG Code: {sr.factoryCode}") print(f"Is Projected: {sr.isProjected}") print(f"Linear Unit: {sr.linearUnitName}") ``` -------------------------------- ### Calculate Field with Python Expression and Code Block Source: https://github.com/esri/arcpy/blob/main/_autodocs/arcpy-core-modules.md Shows how to calculate a field using a simple Python expression for area conversion and a more complex calculation involving a code block to determine zoning based on land use. ```python import arcpy # Simple field calculation arcpy.management.CalculateField( "C:/data/parcels.shp", "AREA_ACRES", "!SHAPE.AREA! / 43560", expression_type="PYTHON3" ) # With code block for complex logic code_block = """ def get_zoning(landuse): if landuse == "Residential": return "R-1" elif landuse == "Commercial": return "C-1" else: return "Other" """ arcpy.management.CalculateField( "C:/data/parcels.shp", "ZONE", "get_zoning(!LANDUSE!)", expression_type="PYTHON3", code_block=code_block ) ``` -------------------------------- ### Create Polyline Geometry Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Shows how to create a Polyline geometry object by defining an array of Point objects that represent the line's vertices. ```python import arcpy # Create vertices for line vertices = [ arcpy.geometry.Point(-118.2437, 34.0522), arcpy.geometry.Point(-118.2432, 34.0525), arcpy.geometry.Point(-118.2425, 34.0530) ] # Create array of points array = arcpy.Array(vertices) # Create polyline polyline = arcpy.geometry.Polyline( array, spatial_reference=arcpy.SpatialReference(4326) ) ``` -------------------------------- ### Delete Features with arcpy Source: https://github.com/esri/arcpy/blob/main/_autodocs/geoprocessing-tools.md Removes selected features from a feature class. This example demonstrates deleting features based on an attribute query after creating a layer and making a selection. ```python arcpy.management.DeleteFeatures(in_features) ``` ```python import arcpy # Delete all features with BUILDING_ID = 'B999' layer = "buildings_layer" arcpy.management.MakeFeatureLayer("C:/data/buildings.shp", layer) arcpy.management.SelectLayerByAttribute(layer, "NEW_SELECTION", "BUILDING_ID = 'B999'") arcpy.management.DeleteFeatures(layer) ``` -------------------------------- ### Update Feature Attributes Source: https://github.com/esri/arcpy/blob/main/_autodocs/quick-start-guide.md Modify existing feature attributes in a shapefile using an UpdateCursor. This example updates a 'PRICE' field based on the 'AREA' field's value. ```python import arcpy fc = "C:/data/buildings.shp" # Update field values with arcpy.da.UpdateCursor(fc, ["AREA", "PRICE"]) as cursor: for row in cursor: area = row[0] if area > 5000: row[1] = area * 250 cursor.updateRow(row) ``` -------------------------------- ### Open ArcGIS Project and Access Properties Source: https://github.com/esri/arcpy/blob/main/_autodocs/map-layer-objects.md Opens an ArcGIS Pro project and retrieves its home folder and default geodatabase. Lists all maps within the project. ```python import arcpy # Open project project = arcpy.mp.ArcGISProject("C:/projects/my_project.aprx") # Get home folder print(f"Home: {project.homeFolder}") # Get default geodatabase print(f"Default GDB: {project.defaultGeodatabase}") # List all maps maps = project.listMaps() for map_obj in maps: print(f"Map: {map_obj.name}") # Get specific map map_obj = project.listMaps("Map")[0] ``` -------------------------------- ### Add Informational Message Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Use AddMessage to display informational messages in the tool's output window. This is useful for indicating the start of processing or showing details about inputs. ```python import arcpy arpy.AddMessage("Processing started...") arpy.AddMessage(f"Input: {input_fc}") ``` -------------------------------- ### List Tables in Workspace Source: https://github.com/esri/arcpy/blob/main/_autodocs/common-utilities.md Lists all tables in the current workspace. Can filter by a wildcard pattern. ```Python import arcpy arcpy.env.workspace = "C:/gdb.gdb" # List all tables tables = arcpy.ListTables() for table in tables: print(f"Table: {table}") # List by pattern arcpy.AddMessage(f"Found {len(tables)} tables") ``` -------------------------------- ### Create Spatial Reference from File Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Creates a SpatialReference object by reading from a projection (.prj) file. ```python sr = arcpy.SpatialReference() sr.createFromFile("C:/projections/custom.prj") ``` -------------------------------- ### Project Feature Class Source: https://github.com/esri/arcpy/blob/main/_autodocs/geoprocessing-tools.md Reprojects a feature class to a new coordinate system. Ensure the target spatial reference is correctly defined, for example, using arcpy.SpatialReference(4326) for WGS84. ```Python import arcpy # Reproject to WGS84 arcpy.management.Project( "C:/data/features_utm.shp", "C:/output/features_wgs84.shp", arcpy.SpatialReference(4326) ) ``` -------------------------------- ### Add Warning Message Source: https://github.com/esri/arcpy/blob/main/_autodocs/script-tools-gp.md Use AddWarning to alert the user about potential issues that do not necessarily stop the script but might require attention. For example, if an input has fewer features than expected. ```python import arcpy if feature_count < 10: arcpy.AddWarning("Input feature class has fewer than 10 features") ``` -------------------------------- ### Building Footprint Analysis Script Source: https://github.com/esri/arcpy/blob/main/_autodocs/quick-start-guide.md This script analyzes building footprints by zone. It sets up the workspace, performs a spatial join, calculates the area of buildings in acres, and generates summary statistics by zone. Ensure input shapefiles and the workspace directory exist. ```python import arcpy def analyze_building_footprints(): """Analyze building footprints by zone.""" try: # Setup arcpy.env.workspace = "C:/analysis" arcpy.env.overwriteOutput = True # Input data buildings = "buildings.shp" zones = "zones.shp" output = "buildings_by_zone.shp" # Validate inputs if not arcpy.Exists(buildings): raise FileNotFoundError(f"Not found: {buildings}") if not arcpy.Exists(zones): raise FileNotFoundError(f"Not found: {zones}") print("Starting analysis...") # Spatial join buildings with zones arcpy.analysis.SpatialJoin( buildings, zones, output, match_option="INTERSECT" ) # Add area field arcpy.management.AddField(output, "AREA_ACRES", "DOUBLE") # Calculate area arcpy.management.CalculateField( output, "AREA_ACRES", "!SHAPE.AREA! / 43560", expression_type="PYTHON3" ) # Get statistics by zone stats_output = "zone_statistics.dbf" arcpy.analysis.Statistics( output, stats_output, [["AREA_ACRES", "SUM"]], case_field="ZONE_ID" ) # Report results with arcpy.da.SearchCursor(stats_output, ["ZONE_ID", "SUM_AREA_ACRES"]) as cursor: print("\nZone Summary:") for zone_id, area in cursor: print(f" Zone {zone_id}: {area:.2f} acres") print("\nAnalysis completed successfully!") return True except Exception as e: print(f"Error: {e}") print(f"Messages: {arcpy.GetMessages()}") return False if __name__ == "__main__": success = analyze_building_footprints() exit(0 if success else 1) ``` -------------------------------- ### Create Buffer Features Source: https://github.com/esri/arcpy/blob/main/_autodocs/geoprocessing-tools.md Creates buffer polygons around input features. Supports variable distances and geodesic calculations. ```Python import arcpy # Simple buffer arcpy.analysis.Buffer( "C:/data/roads.shp", "C:/output/road_buffer.shp", "100 Meters" ) # Variable distance buffer arcpy.analysis.Buffer( "C:/data/facilities.shp", "C:/output/facility_buffers.shp", "BUFFER_DISTANCE" ) # Geodesic buffer arcpy.analysis.Buffer( "C:/data/global_features.shp", "C:/output/global_buffer.shp", "1000 Kilometers", method="GEODESIC" ) ``` -------------------------------- ### Accessing All Fields in a Feature Class Source: https://github.com/esri/arcpy/blob/main/_autodocs/describe-objects.md Use arcpy.Describe to get all fields from a feature class. This snippet shows how to iterate through all fields and access specific properties like name, type, precision, and scale. ```python import arcpy fc = "C:/gdb.gdb/buildings" desc = arcpy.Describe(fc) # Get all fields all_fields = desc.fields # Get specific field for field in all_fields: if field.name == "SQUARE_FOOTAGE": print(f"Found field: {field.name}") print(f"Type: {field.type}") print(f"Precision: {field.precision}") print(f"Scale: {field.scale}") break ``` -------------------------------- ### Describe Function Basic Usage Source: https://github.com/esri/arcpy/blob/main/_autodocs/describe-objects.md Demonstrates the basic syntax for using arcpy.Describe() with different data types. This function returns a descriptor object specific to the data type. ```Python import arcpy # Describe feature class desc = arcpy.Describe("C:/gdb.gdb/buildings") print(f"Type: {desc.dataType}") print(f"Shape Type: {desc.shapeType}") print(f"Feature Type: {desc.featureType}") # Describe raster desc = arcpy.Describe("C:/rasters/elevation.tif") print(f"Type: {desc.dataType}") print(f"Pixel Type: {desc.pixelType}") print(f"Bands: {desc.bandCount}") # Describe shapefile desc = arcpy.Describe("C:/data/roads.shp") print(f"Type: {desc.dataType}") print(f"Fields: {[f.name for f in desc.fields]}") ``` -------------------------------- ### Create and Add Layer File to Map Source: https://github.com/esri/arcpy/blob/main/_autodocs/map-layer-objects.md Instantiate a LayerFile object from a .lyrx or .lyr file and add it to a specified map. The layer is added to the bottom of the map's table of contents. ```python arcpy.mp.LayerFile(path) ``` ```python import arcpy # Create layer file reference layer_file = arcpy.mp.LayerFile("C:/layers/buildings.lyrx") # Add to map project = arcpy.mp.ArcGISProject("C:/projects/my_project.aprx") map_obj = project.listMaps("Map")[0] map_obj.addLayer(layer_file, "BOTTOM") ``` -------------------------------- ### ListTables() Source: https://github.com/esri/arcpy/blob/main/_autodocs/common-utilities.md Lists all tables in the current workspace, with an option to filter by a wildcard pattern. ```APIDOC ## ListTables() ### Description Lists all tables in the current workspace. Results can be filtered using a wildcard pattern for table names. ### Method `arcpy.ListTables(wild_card=None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **wild_card** (str) - Optional - Pattern to match table names ### Returns List of table names ### Usage Example ```python import arcpy arcpy.env.workspace = "C:/gdb.gdb" tables = arcpy.ListTables() for table in tables: print(f"Table: {table}") arcpy.AddMessage(f"Found {len(tables)} tables") ``` ``` -------------------------------- ### Create SpatialReference Object Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Instantiate a SpatialReference object using a well-known ID, WKT string, or a projection file. ```python arcpy.SpatialReference(wellknown_id) arcpy.SpatialReference(wkt_string) arcpy.SpatialReference(projection_file) ``` -------------------------------- ### Clone ArcGIS Pro Python Environment Source: https://github.com/esri/arcpy/blob/main/_autodocs/python-distributions.md This command clones the current ArcGIS Pro Python environment, creating a separate copy for development purposes. This helps in managing dependencies without affecting the base installation. ```python # Clone the ArcGIS Pro environment arcpy.CreateEnv() ``` -------------------------------- ### Get Raster Properties with Describe Source: https://github.com/esri/arcpy/blob/main/_autodocs/raster-analysis.md Use the `arcpy.Describe` object to retrieve detailed properties of a raster dataset, such as pixel type, dimensions, cell size, and spatial reference. This is useful for understanding raster characteristics before analysis. ```python import arcpy raster = "C:/rasters/elevation.tif" # Use Describe to get properties desc = arcpy.Describe(raster) print(f"Pixel Type: {desc.pixelType}") print(f"Band Count: {desc.bandCount}") print(f"Rows: {desc.rowCount}") print(f"Columns: {desc.columnCount}") print(f"Cell Size: {desc.cellSize}") print(f"Spatial Reference: {desc.spatialReference.name}") print(f"Extent: {desc.extent}") print(f"No Data: {desc.noDataValue}") ``` -------------------------------- ### List All ArcPy Environment Settings Source: https://github.com/esri/arcpy/blob/main/_autodocs/environment-settings.md Iterates through all available environment settings in arcpy.env and prints their current values if they are simple data types. Useful for inspecting the current state of all environments. ```python import arcpy # List all current environment settings for setting in dir(arcpy.env): if not setting.startswith('_'): try: value = getattr(arcpy.env, setting) if isinstance(value, (str, int, float, bool, type(None))): print(f"{setting}: {value}") except: pass ``` -------------------------------- ### Create Simple Point Feature Class Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Use this snippet to create a new point feature class in a specified workspace with a defined spatial reference. ```Python import arcpy # Create a simple point feature class arcpy.management.CreateFeatureclass( "C:/gdb.gdb", "sample_points", "POINT", spatial_reference=arcpy.SpatialReference(4326) ) ``` -------------------------------- ### Get Data Summary Information Source: https://github.com/esri/arcpy/blob/main/_autodocs/describe-objects.md Retrieves a summary of a feature class, including its name, type, shape type, field count, row count, extent, and spatial reference. Useful for initial data inspection and logging. ```python import arcpy def get_data_summary(fc_path): """Get comprehensive data summary.""" desc = arcpy.Describe(fc_path) summary = { "Name": desc.name, "Type": desc.dataType, "Shape Type": getattr(desc, "shapeType", "N/A"), "Field Count": desc.fieldCount, "Row Count": getattr(desc, "rowCount", "N/A"), "Extent": str(desc.extent), "Spatial Reference": desc.spatialReference.name if hasattr(desc, "spatialReference") else "N/A" } for key, value in summary.items(): print(f"{key}: {value}") return summary # Usage get_data_summary("C:/gdb.gdb/buildings") ``` -------------------------------- ### Query Features by Where Clause Source: https://github.com/esri/arcpy/blob/main/_autodocs/feature-classes-geometries.md Select features from a feature class based on a SQL-like where clause. Ensure the feature class path and where clause are correctly defined. ```python import arcpy fc = "C:/gdb.gdb/buildings" # Simple where clause where_clause = "SQUARE_FOOTAGE > 5000" with arcpy.da.SearchCursor(fc, ["OBJECTID", "BUILDING_ID"], where_clause) as cursor: for row in cursor: print(f"OID: {row[0]}, ID: {row[1]}") ``` -------------------------------- ### Update Records with a WHERE Clause Source: https://github.com/esri/arcpy/blob/main/_autodocs/data-access-cursors.md Demonstrates how to update records that match a specific SQL WHERE clause. This is useful for targeted data modifications. ```python import arcpy fc = "C:/gdb.gdb/buildings" # Update with WHERE clause where = "SQUARE_FOOTAGE IS NULL" with arcpy.da.UpdateCursor(fc, ["BUILDING_ID", "SQUARE_FOOTAGE"], where) as cursor: for row in cursor: # Set missing values row[1] = 0 cursor.updateRow(row) ``` -------------------------------- ### Accessing Standard Parallel Parameters Source: https://github.com/esri/arcpy/blob/main/_autodocs/spatial-reference-types.md Retrieve the first and second standard parallel latitudes for conic projection systems. This is useful for understanding the geometry of projections like Albers Equal Area and Lambert Conformal Conic. ```python sr = arcpy.SpatialReference(3857) parallel1 = sr.standardParallel1 # First reference latitude parallel2 = sr.standardParallel2 # Second reference latitude ``` -------------------------------- ### Access and Insert Data with ArcPy Cursors Source: https://github.com/esri/arcpy/blob/main/_autodocs/data-access-cursors.md Demonstrates how to use SearchCursor to read data from a table and InsertCursor to add new rows. Ensure the table path is correct and the field names match the table schema. ```python import arcpy # Access table table = "C:/gdb.gdb/building_metadata" with arcpy.da.SearchCursor(table, ["BUILDING_ID", "OWNER", "YEAR_BUILT"]) as cursor: for row in cursor: print(f"ID: {row[0]}, Owner: {row[1]}, Year: {row[2]}") # Insert into table with arcpy.da.InsertCursor(table, ["BUILDING_ID", "OWNER"]) as cursor: cursor.insertRow(["B100", "John Doe"]) ``` -------------------------------- ### List Datasets in Workspace Source: https://github.com/esri/arcpy/blob/main/_autodocs/common-utilities.md Lists all datasets (feature classes and rasters) in the workspace. Can filter by a wildcard pattern or dataset type. ```Python import arcpy arcpy.env.workspace = "C:/gdb.gdb" # List all datasets datasets = arcpy.ListDatasets() for dataset in datasets: print(f"Dataset: {dataset}") ``` -------------------------------- ### Basic Raster Math with ArcPy Source: https://github.com/esri/arcpy/blob/main/_autodocs/raster-analysis.md Perform basic arithmetic operations on rasters. Ensure the Spatial Analyst extension is checked out before use. ```Python import arcpy from arcpy.sa import * # Enable Spatial Analyst arcpy.CheckOutExtension("Spatial") # Load raster dem = Raster("C:/rasters/elevation.tif") # Perform calculations result = dem * 0.3048 # Convert feet to meters result.save("C:/output/elevation_meters.tif") # More complex expressions dem2 = Raster("C:/rasters/elevation_2.tif") difference = dem - dem2 difference.save("C:/output/elevation_change.tif") ```