Search code examples
numpytranspose

Concatenate List of tuples whose elements are numpy arrays


I have a list as shown below

>>> x
[
(array([1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j ]), array([0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j ])), 
(array([1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j ]), array([0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j ])), 
(array([1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j ]), array([0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j ]))
]

My requirement is to concatenate this array into two 1D arrays such that the first element in each tuple being concatenated into one 1D array and second element into the second 1D array.

Expected End result

[
[1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j, 1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j, 1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j],
[0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j, 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j, 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j]
]

Ideal solution would use some standard function in numpy library without explicit loops. Could someone please shed some light on this ?


Solution

  • You cannot vectorize operations with object arrays (in the sense of a fast low level operation).

    You have to use a loop.

    You could go with:

    out = [np.concatenate(y) for y in zip(*x)]
    

    Output:

    [
    array([1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j, 1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j, 1. +0.j , 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j]),
    array([0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j, 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j, 0.5+0.5j, 0. +0.j , 0.5-0.5j, 1. +0.j , nan+0.j])
    ]