Reputation: 4807
I have a list of arrays of same size. The list 'z' holds:
>>> z[0]
Out[24]: array([ -27.56272878, 952.8099842 , -3378.58996244, 4303.9692863 ])
>>> z[1]
Out[25]: array([ -28, 952 , -36244, 2863 ])
>>> z[0].shape
Out[26]: (4,)
I want to concatenate the arrays in the list to obtain a new array which looks like:
-27.56272878 952.8099842 -3378.58996244 4303.9692863
-28 952 -36244 2863
i.e. for the example above I am looking to obtain an array of size ( 2, 4 )
The original list 'z' has about 100 arrays in it but all are of same size (4,)
Edit: I tried suggestions from this threads but doesnt work: Python concatenating different size arrays stored in a list
Upvotes: 3
Views: 8706
Reputation: 1782
Just use extend() and that should be it. Basically extends the initial array with new values.
arr1 = [ -27.56272878, 952.8099842 , -3378.58996244, 4303.9692863 ]
arr2 = [ -28, 952 , -36244, 2863 ]
arr1.extend(arr2)
print arr1
>> [-27.56272878, 952.8099842, -3378.58996244, 4303.9692863, -28, 952, -36244, 2863]
Upvotes: 0
Reputation: 5443
If you have :
z= [np.array([ -27.56272878, 952.8099842 , -3378.58996244, 4303.9692863 ]),
np.array([ -28, 952 , -36244, 2863 ])]
You can try to concatenate them then reshape the new array using the number of arrays concatenated (len(z)
) and the length of each array (len(z[0])
as you said they all have the same length) :
In [10]: new = np.concatenate([i for i in z]).reshape((len(z), len(z[0])))
In [11]: new.shape
Out[11]: (2, 4)
In [12]: print(new)
[[ -2.75627288e+01 9.52809984e+02 -3.37858996e+03 4.30396929e+03]
[ -2.80000000e+01 9.52000000e+02 -3.62440000e+04 2.86300000e+03]]
Upvotes: 1
Reputation: 12782
Use .extend
to build up the new list:
concatenated = []
for l in z:
concatenated.extend(l)
Upvotes: 2