def Frequency(in_table, out_table, frequency_fields, summary_fields=None): import arcpy gp = arcpy # Create list of cursor fields sCursorFields = frequency_fields if not summary_fields is None: sCursorFields += ";" + summary_fields SumFieldList = summary_fields.split(";") else: SumFieldList = [] # Create list of sort fields sSortFields = "" WidthList = [] KeyFieldList = frequency_fields.split(";") for sField in KeyFieldList: WidthList.append(0) if sSortFields == "": sSortFields = sField + " A" else: sSortFields += ";" + sField + " A" # Create summary values KeyList = [] SumTab = {} Rows = gp.SearchCursor(in_table, "", "", sCursorFields, sSortFields) Row = Rows.next() while Row: # Build key sKey = "" i = 0 for sField in KeyFieldList: sVal = str(Row.getValue(sField)) iLen = len(sVal) if iLen > WidthList[i]: WidthList[i] = iLen if sKey == "": sKey = sVal else: sKey += "|" + sVal i += 1 # Get summary values if not SumTab.has_key(sKey): SumList = [1] KeyList.append(sKey) bNewEntry = True else: SumList = SumTab[sKey] SumList[0] = SumList[0] + 1 bNewEntry = False i = 0 for sField in SumFieldList: i += 1 if bNewEntry: SumList.append(Row.getValue(sField)) else: SumList[i] = SumList[i] + Row.getValue(sField) SumTab[sKey] = SumList Row = Rows.next() # Create output table import os.path sOutWorkspace = os.path.dirname(out_table) sOutTabName = os.path.basename(out_table) gp.CreateTable_management(sOutWorkspace, sOutTabName) gp.Workspace = sOutWorkspace i = 0 for sField in KeyFieldList: iLen = WidthList[i] gp.AddField_management(sOutTabName, sField, "text", "#", "#", str(iLen)) i += 1 gp.AddField_management(sOutTabName, "Count", "long") for sField in SumFieldList: gp.AddField_management(sOutTabName, sField, "double") # Populate output table Rows = gp.InsertCursor(sOutTabName) for sKey in KeyList: Row = Rows.newRow() ValList = sKey.split("|") SumList = SumTab[sKey] i = 0 for sField in KeyFieldList: sVal = ValList[i] Row.setValue(sField, sVal) i += 1 Row.setValue("Count", SumList[0]) i = 0 for sField in SumFieldList: i += 1 Row.setValue(sField, SumList[i]) Rows.insertRow(Row) # All done!