Trying to figure out how to populate two fields based on two fields. I need to be able to populate say F_ID3 with the number of occurrences of F_ID1 then in F_D4 add the text of the occurrences from F_ID2. Like below, note that their may be empty or nulls in the fields
Currently have this
OBJECTID | F_ID1 | F_ID2 |
1 | aa1123 | 12345 |
2 | aa1123 | 12346 |
3 | BB3361 | 67891 |
4 | BB3361 | 67892 |
5 | BB3361 | 67893 |
6 | UU9832 | 11123 |
7 | PP2225 | 6989 |
8 | PP2225 | 6988 |
I need this
OBJECTID | F_ID1 | F_ID2 | F_ID3 | F_ID4 |
1 | aa1123 | 12345 | 2 | 12345, 12346 |
2 | aa1123 | 12346 | ||
3 | BB3361 | 67891 | 3 | 67891, 67892, 37893 |
4 | BB3361 | 67892 | ||
5 | BB3361 | 67893 | ||
6 | UU9832 | 11123 | 1 | 11123 |
7 | PP2225 | 6989 | 2 | 6988, 6989 |
8 | PP2225 | 6988 |
Quick and dirty, haven't tested, but may work for you:
import arcpy
from collections import defaultdict
lyr =
fields = ["F_ID1", "F_ID2", "F_ID3", "F_ID4"]
sql = "ORDER BY F_ID1, F_ID2, OBJECTID"
d = defaultdict(list)
with arcpy.da.UpdateCursor(lyr, fields, sql_clause=(None,sql)) as cur:
for id1, id2, id3, id4 in cur:
d[id1] += id2
cur.reset()
id1, id2, id3, id4 = next(cur)
cur.updateRow([id1, id2, len(d[id1]), ",".join(d[id1])])
id_prev = id1
for id1, id2, id3, id4 in cur:
if id1 == id_prev: continue
cur.updateRow([id1, id2, len(d[id1]), ",".join(d[id1])])
id_prev = id1
I wasn't getting what I needed from the code you provided but I was able to make the following work based on the code you provided. It's not as clean as yours but I am a newbie to python. Thanks.
#populate F_ID3 & F_ID4
dict1 = dict()
with arcpy.da.SearchCursor(fc,['F_ID1','F_ID3','F_ID2']) as cursor:
for row in cursor:
dict1.setdefault(row[0],[]).append(str(row[2]))
with arcpy.da.UpdateCursor(fc,['F_ID1','F_ID3','F_ID4']) as cursor:
for row in cursor:
row[2] = ",".join(dict1[row[0]])
cursor.updateRow(row)
#Populate F_ID3
with arcpy.da.UpdateCursor(fc, ["F_ID1", "F_ID3"]) as cur:
cnt = Counter(row[0] for row in cur)
cur.reset()
for row in cur:
cur.updateRow([row[0], cnt.pop(row[0], None)])