Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append 2 dimensional arrays to one single array

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?

like image 758
gustavgans Avatar asked Dec 26 '22 00:12

gustavgans


1 Answers

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.

like image 115
gg349 Avatar answered Jan 11 '23 06:01

gg349