Zanam
Zanam

Reputation: 4807

Python concatenate arrays in a list

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

Answers (4)

admix
admix

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

mgc
mgc

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

screenpaver
screenpaver

Reputation: 1130

Won't this do it?

znew = np.vstack((z[0],z[1]))

Upvotes: 4

Fabricator
Fabricator

Reputation: 12782

Use .extend to build up the new list:

concatenated = []
for l in z:
    concatenated.extend(l)

Upvotes: 2

Related Questions