Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
[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])
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading