3

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

1
  • With numpy concatenation issues you need to pay attention to the shape and dimensions of the arrays. Look at the code for functions like vstack and hstack to understand how they use concatenate. Commented Jan 14, 2016 at 20:31

4 Answers 4

4

Won't this do it?

znew = np.vstack((z[0],z[1]))
Sign up to request clarification or add additional context in comments.

Comments

2

Use .extend to build up the new list:

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

Comments

1

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

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.