[SOLVED] flatten list of numpy arrays while keeping inner arrays

Issue

l = [np.array([[1,2],[3,4]]), np.array([5,6]), np.array([[7,8],[9,10],[11,12]])]

I’m trying to flatten this list of arrays but keeping the inner arrays:

[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]

I tried itertools.chain, np.concatenate, np.flatten but none of these options give the output above

Solution

Your arrays have different numbers of dimensions, you need to ensure they all are 2D:

out = np.concatenate([x[None,:] if x.ndim == 1 else x for x in l])

output:

array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10],
       [11, 12]])

or with itertools.chain with a list output:

from itertools import chain
list(chain.from_iterable([x.tolist()] if x.ndim == 1 else x.tolist()
                         for x in l))

output: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]

Answered By – mozway

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *