2

I have the following code to calculate the number of wells within a counties layer. Right now it is giving me a total number of wells.

Where and how do I get it to loop through all the counties separately and give me that count separately?

Following this; I'd like to also calculate the well density – i.e. how many wells there are per area unit, and update the table with that value as well.

import arcpy

# For each county calculate the total numbers of wells that fall into that county, and update the county table with the total count.

wellsLayer = "C:\\Wells.shp"
arcpy.MakeFeatureLayer_management(wellsLayer , "wells_lyr")

countiesLayer = "C:\\COUNTIES.shp"

arcpy.SelectLayerByLocation_management("wells_lyr", "INTERSECT", countiesLayer, "", "NEW_SELECTION")

fieldList = "name"

wellsCount = int(arcpy.GetCount_management("wells_lyr").getOutput(0))

print wellsCount
1

When you do a spatial join analysis the output shapefile adds a new field "Join_Count" by default in which you can find how many wells are located in each county.

The following example use arcpy.da.SearchCursor() to give the information about the number of wells in each county after performing the Spatial join analysis.

import arcpy
from arcpy import env
env.workspace = r"F:\Test"

targetFeature = "county.shp"
joinFeature = "well.shp"

arcpy.SpatialJoin_analysis(targetFeature,joinFeature,"SpatialJoinTest.shp")

with arcpy.da.SearchCursor("SpatialJoinTest.shp",["id","Join_Count"]) as cursor:
    for row in cursor:
        county_id = row[0]
        well_count = row[1]
        print "There are {0} wells in county id {1}".format(well_count, county_id)

del row
del cursor

Te output is like this:

There are 0 wells in county id 0
There are 31 wells in county id 1
There are 933 wells in county id 2
There are 548 wells in county id 3
There are 8 wells in county id 4
There are 222 wells in county id 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy