'Transform array of arrays to a single array
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?
Solution 1:[1]
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])]
Solution 2:[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])
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aivar Paalberg |
Solution 2 | |
Solution 3 | Sherin Jayanand |