Home > other >  flatten list of numpy arrays while keeping inner arrays
flatten list of numpy arrays while keeping inner arrays

Time:03-17

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

CodePudding user response:

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]]

CodePudding user response:

You haven't provided your desired output. But, as I understood, you are looking for this:

x = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
print([n for m in x for n in m])

with output:

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

Please let me know if this is not your desired output.

  • Related