pythonarraysinterleavelinspace

Python, interleaving two or more linspace arrays


I have three linspace arrays of equal length: a, b, and c. I want to interleave the arrays together in the following way.

([a[0], b[0], c[0]], [a[1], b[1], c[1]], [a[2], b[2], c[2]], . . . etc.)

I've seen numerous examples of interleaving two or more arrays, but nothing that groups associated values together. I need it this way because in my arrays, a[0] is associated with b[0] and c[0]. When I print the resulting interleave array which values are associated with each other without having to count from the very beginning.

I've looked around for different solutions, but I have not been able to find examples of interleaving arrays that group associated values together.


Solution

    1. Add a new axis of size 1 as the second axis for each array and concatenate them along the new axis.
    import numpy as np
    
    a, b, c = np.linspace(0, 4, 3), np.linspace(1, 5, 3), np.linspace(2, 6, 3)
    print(a, b, c)
    # [0. 2. 4.] [1. 3. 5.] [2. 4. 6.]
    
    result = np.concatenate([x.reshape(x.shape[0], 1, *(x.shape[1:])) for x in (a, b, c)], axis=1)
    
    print(result)
    # [[0. 1. 2.] 
    #  [2. 3. 4.] 
    #  [4. 5. 6.]]
    
    1. If you regard arrays as lists, you can also use zip.
    result = np.array(list(zip(a, b, c)))
    print(result)