1

I am after doing a COUNTIFS in python. I need to check each row ± 250 with other rows and if this row is between that range then count 1, then next row, .. and do the same thing. and if there are any, put the total number, else put 1. Here's the code in excel: COUNTIFS(D:D,D2,E:E,">="&E2-$G$2,E:E,"<="&E2+$G$2)

enter image description here

Here's the code, but it's not doing countifs.

import arcpy
fc = "feature_class"
counter = 0

with arcpy.da.UpdateCursor(fc,("Mean_m","Count")) as cursor:
    for row in cursor:
        if row[0] >= row[0]-250 and row[0] <= row[0]+250:
            counter += 1
            row[1] = counter
        else:
            counter = 1
            row[1] = counter
        cursor.updateRow(row)
  • what are the errors? – Midavalo May 3 '16 at 7:17
  • with arcpy.da.UpdateCursor you don't need setValue - just do row[1] = counter – Midavalo May 3 '16 at 7:18
  • lets say the value of row[0] is 500. Your if statement is saying "if 500 is greater than or equal to 250 and 500 is less than or equal to 750" - it'll always return True. – Midavalo May 3 '16 at 7:27
  • Your updateRow line should be cursor.updateRow(row). And since you're using with you don't need to del row, rows as with drops those once complete. – Midavalo May 3 '16 at 7:29
  • 1
    @Matt you should edit your question and include all the extra detail to make it clear what you are asking, and also update any code that is now working – Midavalo May 3 '16 at 7:57
3

If I understand what you're after, I think something like this should work:

import arcpy
fc = "feature_class"

fields = ["Mean_m","Count"]

meanVals = []

with arcpy.da.SearchCursor(fc,fields) as cursor:
    for row in cursor:
        meanVals.append(row[0])

with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        counter = 0
        for mean in meanVals:
            if row[0] >= mean -250 and row[0] <= mean+250:
                counter += 1
        row[1] = counter
        cursor.updateRow(row)

SearchCursor creates a list of all the values in Mean_m, and then the UpdateCursor loops through this list and counts how many times your current row's Mean_m is within ±250 in the list. It then writes that count to Count for the current row. No need to use an else as it will always find at least one instance (the current row).

You might need to include a check or workaround for Null values if they exist.

  • +1 : it seems to be what OP is looking for. Note that you could use row[1]= sum(1 for x in meanVals if abs(row[0]-x) <=250 ) – radouxju May 3 '16 at 12:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.