2
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

1
  • 1
    np.vstack(l) ? Commented Mar 17, 2022 at 13:45

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

You basically need to flatten each subarray, concatenate them and finally reshape it.

np.concatenate(list(map(np.ravel, l))).reshape(-1, 2)

output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.