Good day everybody,
I am currently working with a feature class. I have a field with each cat that could be repeated around 100 or more times. However, I have 25 different cats.
My task is to count how many times each cat appears in the field. Currently, I have a total number 40000 when I use "numbermyList = len(myList)" after my loop and only one when I use it in the loop. When I use "numbermyList = len(cat)", it gives the total number only for the first cat but not working the other cats.(If i use inside or outside of the loop)
Could you please recommend to me how to use the loop to count the number of each cat in my field?
Certainly, I would like to use the received number in my next loop, so I will receive something like this: 1st cat = 4000(numbermyList = len(myList)), 2sd cat 5000 and so on (numbermyList = len(myList)).
Solved! Go to Solution.
cat_names = ["cat_1", "cat_2", "cat_3", "cat_25"]
cat_numbers = []
for name in cat_names:
sql_query = "CatName = '{}'".format(name)
cat_rows = [c for c in arcpy.da.SearchCursor("Cat_Layer", ["CatName"], sql_query)]
cat_numbers.append(len(cat_rows))
for name, number in zip(cat_names, cat_numbers):
print("{} appeared {} times in Cat_Layer.".format(name, number))
#cat_1 appeared 56 times in Cat_Layer.
#...
#cat_25 appeared 572 times in Cat_Layer.
You can use a default dictionary for this!
from collections import defaultdict
fakeCursor = ["one", "three", "two", "one", "one", "two", "five", "nine"]
counter = defaultdict(int)
for i in fakeCursor:
counter[i] += 1
print counter
Output:
defaultdict(<type 'int'>, {'nine': 1, 'five': 1, 'three': 1, 'two': 2, 'one': 3})
Can you elaborate a bit on this? Do you mean you want the count of occurrences per cat, something like:
cat 1: 100
cat 2: 2500
etc...
I think part of the problem here is that the myList object is being redefined as an empty list for every iteration.
Since there is a bit of confusion over what you are trying to do within your loop, I suggest you step back from tools and solutions and explain a bit what your requirement is, i.e., just describe what you are trying to achieve overall.
cat_names = ["cat_1", "cat_2", "cat_3", "cat_25"]
cat_numbers = []
for name in cat_names:
sql_query = "CatName = '{}'".format(name)
cat_rows = [c for c in arcpy.da.SearchCursor("Cat_Layer", ["CatName"], sql_query)]
cat_numbers.append(len(cat_rows))
for name, number in zip(cat_names, cat_numbers):
print("{} appeared {} times in Cat_Layer.".format(name, number))
#cat_1 appeared 56 times in Cat_Layer.
#...
#cat_25 appeared 572 times in Cat_Layer.
Do you have other CatName values in Cat_Layer that aren't in cat_names? In other words, do you want to count all occurrences of every CatName value or only the ones you explicitly define?
Good question. In that case, you would run this before:
cat_names = [c[0] for c in arcpy.da.SearchCursor("Cat_Layer", ["CatName"])]
cat_names = list(set(cat_names)) # names of all cats in Cat_Layer