Combine rows within table based on if there is any data populated- Using Python

04-26-2017 01:13 PM
New Contributor

Basically I am focusing on 2 fields.

fields[0] = Apple

fields[1] = Grape

fields[2] = Pear

What I want in English:

If Apple has data and Pear has no data

      Pear =  Apple

If Grape has data and Pear has no data

   Pear = Grape

Otherwise: Pear = Pear 

   *All 3 columns will never be populated, as well as Apple and Grape will never be populated simultaneously

I tried making up a script using Notepad ++ but it is not translating at all and the results are just reading the columns as their original data.

I know this is wrong but I do not know what would be right.


0 Kudos
3 Replies
MVP Esteemed Contributor

Since Apple and Grape will never be populated simultaneously, and you only want to populate Pear if it has no data, the following should work in the Field Calculator expression (make sure to select Python parser):

(!Apple! or !Grape!) if !Pear! is None else !Pear!

The above is using a Python Conditional Expression, a.k.a., ternary operator.

MVP Esteemed Contributor

Based on you description, you have limited possibilities of combinations, hence, have a look at this to ensure that you aren't missing any possibilities

rows = [['A', None, None],
        [None, 'G', None],
        [None, None, 'P'],
        [None, None, None]
for row in rows:
    if row[2] is None:
        row[2] = [row[0], row[1]][row[0] is None]
    print("row... {}".format(row))

# which yields...

row... ['A', None, 'A']
row... [None, 'G', 'G']
row... [None, None, 'P']
row... [None, None, None]
MVP Honored Contributor

At some point, you'll also have to change your fields list to include strings, not unspecified variables:

fields = ['Apple','Grape','Pear']

Also, you need to call the following to actually update the row:

0 Kudos