Janny Loco
Janny Loco

Reputation: 465

Flatten numpy array with python

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?

Upvotes: 1

Views: 511

Answers (2)

BENY
BENY

Reputation: 323226

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

Upvotes: 5

Sociopath
Sociopath

Reputation: 13401

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]

Upvotes: 1

Related Questions