Time for action – stacking arrays

First, set up some arrays:

In: a = arange(9).reshape(3,3)
In: a
Out:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In: b = 2 * a
In: b
Out:
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
  1. Horizontal stacking: Starting with horizontal stacking, form a tuple of the ndarray objects and give it to the hstack() function as follows:
    In: hstack((a, b))
    Out:
    array([[ 0,  1,  2,  0,  2,  4],
           [ 3,  4,  5,  6,  8, 10],
           [ 6,  7,  8, 12, 14, 16]])
    

    Achieve the same with the concatenate() function as follows (the axis argument here is equivalent to axes in a Cartesian coordinate system and corresponds to the array dimensions):

    In: 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]]) ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.