I have a loop over 2-dimensional np.arrays() and I need to add these arrays to one single array.
in plain Python I would do this
In [37]: a1 = [[1,2],[3,4]]
In [38]: b1 = [[5,6],[7,8]]
In [39]: l1 = []
In [40]: l1.append(a1)
In [41]: l1.append(b1)
In [42]: l1
Out[42]: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
How do I get the same result with numpy for l1?
Just use:
l1 = np.array([a1,b1])
Notice also that in numpy
you don't append to arrays. You allocate them first, and then you fill them:
import numpy as np
a1 = np.array([[1,2],[3,4]])
b1 = np.array([[5,6],[7,8]])
#allocate exact size of the final array
l1 = empty(((2,)+a1.shape),dtype=a1.dtype)
l1[0]=a1
l1[1]=b1
or you use one of the many helper functions (dstack
,hstack
,concatenate
described by the others)
EDIT: I find both solutions above very readable and close to python lists syntax, but this is rather subjective. Timing how fast this is, you find that both solutions are marginally faster to the fastest solution proposed by @unutbu, based on concatenate. Notice moreover that this does not create a view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With