Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

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

    This image shows horizontal stacking with the concatenate() function:

  2. Vertical stacking: With vertical stacking, again, a tuple is formed. This time, it is given to the vstack...