Search code examples
pythonarraysnumpyconcatenationstring-concatenation

How to concatenate these arrays per element when the number of arrays are formed from a loop?


I have a bunch of arrays which will be formed from a loop. I know I can concatenate via this method but I can only get it to work for an already established number of arrays:

y1 = ['C1', 'C2', 'C3']
y2 = ['C4', 'C5', 'C6']
z = np.array([a+b for a, b in zip(y1, y2)])

but how do I get it to work if I have many more arrays i.e. if I have these arrays as input going up to array x:

y1 = ['C1', 'C2', 'C3']
y2 = ['C4', 'C5', 'C6']
.
.
.
yx = ['C22', 'C23', 'C24']

And I want to get an output:

z = ['C1C4...C22', 'C2C5...C23', 'C3C6...C24']

Solution

  • You could store all these arrays in another array the moment they are created and then zip the array that contains them as follows:

    import numpy as np
    y1 = ['C1', 'C2', 'C3']
    y2 = ['C4', 'C5', 'C6']
    y = [y1,y2]
    z = np.array(["".join(elem) for elem in zip(*y)])
    print(z)
    

    This will give you:

    ['C1C4' 'C2C5' 'C3C6']