Staking arrays

Arrays can be stacked horizontally, vertically, and depth wise. First we need to create an array to work with.

import numpy as np

a = np.arange(9).reshape(3,3)
b = 2 * a

a
#out
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

b
#out
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])

Horizontal stacking

Using the hstack() method (using a tuple):

np.hstack((a, b))

#out
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])

Using the concatenate() method:

np.concatenate((a, b), axis = 1)

#out
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])

You have to mention the axis otherwise it will stuck it vertically!

Verical stacking

Using the vstack() method (using a tuple):

np.vstack((a, b))

#out
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])

Using the concatenate() method:

np.concatenate((a, b), axis = 0)

#out
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])

You DON’T have to mention the axis, by default it is set to 0!

Depth stacking

Using the dstack() method (with a tuple):

np.dstack((a, b))

#out
array([[[ 0,  0],
        [ 1,  2],
        [ 2,  4]],

       [[ 3,  6],
        [ 4,  8],
        [ 5, 10]],

       [[ 6, 12],
        [ 7, 14],
        [ 8, 16]]])

Using the column_stack() method.

1D arrays are stacked column wise.

import numpy as np

c = np.arange(2)
c

#out
array([0, 1])

d = c * 2
d

#out
array([0, 2])

nd.column_stack((c, d))

#out
array([[0, 0],
       [1, 2]])

2D arrays are stacked the way hstack() stacks them.

np.column_stack((a, b))

#out
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])

Row stacking

Arrays can be stacked row-wise. 1D arrays are stacked into a 2D arrays.

1D arrays:

c = np.arange(2)
d = c * 2
np.row_stack((c, d))

#out
array([[0, 1],
       [0, 2]])

2D arrays are stacked with row_stack() the same way as vstack().

np.row_stack((a, b))

#out
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])

Leave a Reply