Python to concatenate alternating numeric digits from two separate number fields

06-12-2019 11:28 AM
New Contributor II

I have calc'd the X and Y coordinate value using calc geometry into two separate (numeric / double) fields and now need to combine them into a new string field by alternating the values based upon their individual digit position.

Eample: (note: not using any values after the decimal pt)

Field X_Coor                  Field Y_Coor            New Combined_Field

1831548.520524            490651.99297           8439105645

End result should have text value template of 'X2Y1X3Y2X4Y3X5Y4X6Y5' ... OR 8439105645 (using the example above)


0 Kudos
4 Replies
MVP Emeritus
def weave(a, b):
    a = str(a).split(".")[0][1:]
    b = str(b).split(".")[0][:-1]
    return "".join([*sum(zip(a, b), ())])

weave(1831548.520524, 490651.99297)

'weaving' two sequences with conditions.  This is a mini-version of a much larger problem.

Line 3... skip the first number in sequence 'a'

Line 4... skip the last number in sequence 'b'

Line 5... the magic

For a field calculator expression, line 8 would be

weave(!a_field!, !b_field!)

Any further deviations from your example entail greater condition checking and hence a much longer version

MVP Emeritus

PS, I should add you can 'int' or 'float' the string output if you don't need it in string format

0 Kudos
New Contributor II

Thanks Dan,

I loaded your script into the Field Calc w/Prelogic and am receiving errors.

I'm working thru it, but if you have an suggestions ... I'll take them.

I really appreciate your help

0 Kudos
MVP Emeritus

ArcGIS Pro? hence, Python 3?

I would have to see the screen grab of the code block section in the field calculator (which it is initially designed for).

So add a new field, select calculate field, copy and paste the code from a text editor (like notepad or notepad++) into the code block.

It says there is a syntax error in line 5... I am trying to rule out things like format issues, wrong line terminators etc.  So run a check on the syntax.

the starred expression in line 5... can't remember if it was just a python 3 thing, 

0 Kudos