Popoulate fields based on occurrences and text

359
2
10-15-2020 08:41 AM
CCWeedcontrol
Occasional Contributor III

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

OBJECTIDF_ID1F_ID2
1aa112312345
2aa112312346
3BB336167891
4BB336167892
5BB336167893
6UU983211123
7PP22256989
8PP22256988

I need this

OBJECTIDF_ID1F_ID2F_ID3F_ID4
1aa112312345212345, 12346
2aa112312346  
3BB336167891367891, 67892, 37893
4BB336167892  
5BB336167893  
6UU983211123111123
7PP2225698926988, 6989
8PP22256988  
0 Kudos
2 Replies
JoshuaBixby
MVP Esteemed Contributor

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
2Quiker
Occasional Contributor II

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)])‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos