Calculating # of differences between two numerical fields in ArcPro

474
1
05-23-2022 11:25 AM
BarrettLewis1
New Contributor III

Hi all, I have a Calculate Field/Python question. I need to apply fuzzy logic to match addresses. I have two fields, both are for street numbers. I need a script that calculates how many numbers are off between the two fields in terms of number placement, not subtraction. So if one field is 831 and the second field is 842, the result calculation (in a third field) would be 2, because the second and third place numbers are different. If all numbers were different, it would be 3, if none were different it would be 0. 

I'm a super newb when it comes to Python but I do have some working knowledge, just not sure how to conceptualize this. Can anyone suggest a way of going about this task using Python and the Calculate Field option? Open to other options as well. Thank you.

0 Kudos
1 Reply
BlakeTerhune
MVP Regular Contributor

You'd be surprised how many times another person has a similar problem. You just need to know how to search for it. In this case, think of your numbers as strings because each character in a strings are iterable.

I wasn't sure if you'll ever have values that are different lengths so I assumed yes. To handle this case, I had to lean on a function in itertools I'd never heard of called zip_longest and applied it to this solution to sum the occurrences where the positional characters are different.

 

def compare_positional_chars(val1, val2):
    # Import the required library
    from itertools import zip_longest

    # Force the value to string.
    val1 = str(val1)
    val2 = str(val2)

    # Create key/value pairs of positional characters from each input.
    zip_result = zip_longest(val1, val2)

    # Count the number of pairs that don't have the same key and value.
    return sum(1 for x,y in zip_result if x != y)


# Call the function in calculate field with your field names to be compared.
compare_positional_chars(!Field1!, !Field2!)