Tuesday, October 5, 2010

Counting Values Script - Finding Likely Voters

It's election time in the United States, and some of you might be helping out with campaigns.  A colleague of mine who helps out with campaigns asked for my advice on how to make a quick utility to examine who voted in the last four general elections.  From that information, he would categories likely, unlikely, very likely voters. 

Of course I said use python.  It's quick, easy, and reusable:

####################
# Input Parameters #
####################
inputTable = arcpy.GetParameterAsText(0)
CountFields = arcpy.GetParameterAsText(1)
VotedValues = arcpy.GetParameterAsText(2)
###################
# Local Variables #
###################
ElectionCountFieldName= "ElectionCount"
###################
# Logic #
###################
fields = arcpy.ListFields(inputTable)
for field in fields:
if field.name == ElectionCountFieldName:
arcpy.DeleteField_management(inputTable, ElectionCountFieldName)
break
del fields

arcpy.AddField_management(inputTable, ElectionCountFieldName, "TEXT")

rows = arcpy.UpdateCursor(inputTable)
splitVal = VotedValues.split(',')
for row in rows:
count = 0
for f in CountFields:
if str(row.getValue(f)) in splitVal:
count = count + 1
row.setValue(ElectionCountFieldName,str(count))
rows.updateRow(row)
del row, rows
arcpy.SetParameterAsText(3, inputTable)

where the inputTable is the table which contains the data you wish to sum up, CountFields is a collection of field names (multi-value object), and VotedValues is a comma separated string (value1,value2, etc...) that represents the values of a voter voted.

Now that the script is created, you need to create the toolbox in ArcCatalog or ArcMap:



Parameter NameSetup
1Input Table/FCType: Feature Class or Table
2FieldsType: Field,
Obtained From: Parameter 1,
MultiValue: Yes
3Voted ValuesType: String
4Return Table/FCType: Table/FC,
Direction: Output


Enjoy and Happy GISing