Skip to content Skip to sidebar Skip to footer

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.f

Solution 1:

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

Solution 2:

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]

Post a Comment for "Flatten Numpy Array With Python"