Comparing multiple fields to each other within one feature class using Python?

590
6
04-11-2018 07:42 AM
DeidreA
New Contributor

Hello,

So I have a feature class of 5 fields that I'm looking at. I'm looking to compare 4 fields to 2 other fields. Essentially, if any of the first 4 fields match to the other 2 fields then I want to return a "YES" in a new field. If none of the 4 fields match the 2 fields, then I want to return a NO. I started typing this out in the field calculator, but I'm unsure if this is the most efficient method.

I'm a beginner at python, so here is my code below:

def TextValue(MATCH):
  if !JURIS! or !MGMT1! or !MGMT2! or !MGMT3! == !EDC_MGMT! or !EDC_JURIS!:
    return = "YES"
  elif:
    return = "NO"‍‍‍‍‍

Am I going about this the right way? Let me know if my question should be clarified.

0 Kudos
6 Replies
DanPatterson_Retired
MVP Emeritus
a = [1, 2, 3, 4]
b = [2, 4]
sum([True for i in a if i in b])
2

substitute the numbers for your field names.  If the sum is > 0, then it is true, otherwise false

0 Kudos
DeidreA
New Contributor

The only thing is that they're text fields. Unless I'm misunderstanding you? I'm unsure how this would still apply. Also, can I still do this in the field calculator?

Thank you so much for your help!

0 Kudos
DanPatterson_Retired
MVP Emeritus

[0, 1][sum([True for i in [!a!, !b!, !c!, !d!] if i in [!e!, !f!])]

would be a field calculator expression, python parser, a to f are field names

RandyBurton
MVP Alum

If there is more than 1 match, you will get an index error.  Also a bracket is missing.

[0, 1][sum([True for i in [!a!, !b!, !c!, !d!] if i in [!e!, !f!]])]

But it is a nice way to make multiple comparisons.

a = 'a'
b = 'b'
c = 'c'
d = 'd'

e = 'd'
f = 'b'

print sum([True for i in [a, b, c, d] if i in [e, f]])
print "yes" if sum([True for i in [a, b, c, d] if i in [e, f]]) else "no"

# results
2
yes
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
DanPatterson_Retired
MVP Emeritus
a, b, c, d = 'abcd'

e, f = 'ab'

[0, 1][max([True for i in [a, b, c, d] if i in [e, f]])]

1

was using the phone... max is the correct, rather than sum, since it will either be 0 or 1, so even a single 1 will trigger

Again, substitute the letters for your field names

JoshuaBixby
MVP Esteemed Contributor

Try this in the code block:

def TextValue(juris, mgmt1, mgmt2, mgmt3, edc_mgmt, edc_juris):
    s4 = set([juris, mgmt1, mgmt2, mgmt3])
    s2 = set([edc_mgmt, edc_juris])
    
    if s2.intersection(s4)
        return "YES"
    else:
        return "NO"

and call it like this:

TextValue(!JURIS!, !MGMT1!, !MGMT2!, !MGMT3!, !EDC_MGMT!, !EDC_JURIS!)