2

I would like to expand a list of arrays into a single array, so for example:

a = [array([1,2,3]), array([4,5,6]), array([7,8,9,])]

To become:

a = [array([1,2,3,4,5,6,7,8,9])]

How do I do this?

arilwan
  • 3,374
  • 5
  • 26
  • 62
  • Does this answer your question? [Concatenating two one-dimensional NumPy arrays](https://stackoverflow.com/questions/9236926/concatenating-two-one-dimensional-numpy-arrays) – jmkjaer Jun 01 '20 at 11:08

3 Answers3

2

Try using

list.extend

It will work Maybe you want this

from numpy import array
k=[array([1,2,3]), array([4,5,6]), array([7,8,9,])]
l=[]
for i in range(len(k)):
  l.extend(k[i])
print(array(l))

Output:

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

tanmayjain69
  • 158
  • 1
  • 10
2

One option is to convert list to np.array and then flatten inside the list:

>>> import numpy as np
>>> arr = [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9,])]
>>> [np.array(arr).flatten()]
[array([1, 2, 3, 4, 5, 6, 7, 8, 9])]
Aivar Paalberg
  • 4,645
  • 4
  • 16
  • 17
-1

You can use reshape of Numpy to do it:-

a=[[1,2,3],[3,4,5],[6,7,8]]
print("Before:" , a)
import numpy as np
a=np.reshape(a,9)
print("After:",a)

The output:

Before: [[1, 2, 3], [3, 4, 5], [6, 7, 8]]
After: [1 2 3 3 4 5 6 7 8]

Hope this is what you want.

Sherin Jayanand
  • 204
  • 2
  • 9