1

Here is an example to reproduce my problem:

a = np.array([[1,2], [3,4], [6,7]])
b = np.array([[1,2], [3,4], [6,7,8]])
c = np.array([[1,2], [3,4], [6]])
print(a.flatten())
print(b.flatten())
print(c.flatten())

The problem exist when one of the arrays has an item less or more.

Output:
[1 2 3 4 6 7]
[list([1, 2]) list([3, 4]) list([6, 7, 8])] # Won't work
[list([1, 2]) list([3, 4]) list([6])]       # Also won't work

How I want it:
[1 2 3 4 6 7]
[1 2 3 4 6 7 8]
[1 2 3 4 6]

Does anyone know how to flatten the list properly for example b and c?

1
  • 1
    flatten works on 2d arrays; it changes the shape. Your b (and 'c') is not 2d; it's 1d, already flat. You might need to step back and (re)read numpy documentation about shape (and flatten and dtype). Commented Oct 24, 2018 at 16:48

2 Answers 2

5

Using concatenate

np.concatenate(b)
Out[204]: array([1, 2, 3, 4, 6, 7, 8])
np.concatenate(c)
Out[205]: array([1, 2, 3, 4, 6])
Sign up to request clarification or add additional context in comments.

Comments

1

You need:

from itertools import chain

a = np.array([[1,2], [3,4], [6,7]])

b = np.array([[1,2], [3,4], [6,7,8]])

c = np.array([[1,2], [3,4], [6]])

print(a.flatten())
print(list(chain(*b)))
print(list(chain(*c)))

Output:

[1 2 3 4 6 7]
[1 2 3 4 6 7 8]
[1 2 3 4 6]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.