To stack a sequence of NumPy arrays horizontally or vertically

To stack a sequence of NumPy arrays horizontally or vertically, you can use the numpy.hstack() and numpy.vstack() functions, respectively. These functions allow you to concatenate arrays along different axes. Here are examples of both methods:

  1. Horizontal stacking using numpy.hstack():
   import numpy as np

   # Create the arrays
   arr1 = np.array([1, 2, 3])
   arr2 = np.array([4, 5, 6])
   arr3 = np.array([7, 8, 9])

   # Stack the arrays horizontally
   hstacked_arr = np.hstack((arr1, arr2, arr3))

   print(hstacked_arr)

Output:

   [1 2 3 4 5 6 7 8 9]

In this example, we have three 1D arrays arr1, arr2, and arr3. Using np.hstack((arr1, arr2, arr3)), we horizontally stack the arrays together, resulting in a single 1D array hstacked_arr containing the elements of all the input arrays.

  1. Vertical stacking using numpy.vstack():
   import numpy as np

   # Create the arrays
   arr1 = np.array([1, 2, 3])
   arr2 = np.array([4, 5, 6])
   arr3 = np.array([7, 8, 9])

   # Stack the arrays vertically
   vstacked_arr = np.vstack((arr1, arr2, arr3))

   print(vstacked_arr)

Output:

   [[1 2 3]
    [4 5 6]
    [7 8 9]]

In this example, we have three 1D arrays arr1, arr2, and arr3. Using np.vstack((arr1, arr2, arr3)), we vertically stack the arrays together, resulting in a 2D array vstacked_arr where each row corresponds to one of the input arrays.

Run Code In Live & Test

Conclusion:

Both numpy.hstack() and numpy.vstack() functions can accept a tuple of arrays as input, allowing you to stack multiple arrays together. These functions are useful for combining arrays along different axes, either horizontally or vertically, to create larger arrays or to align arrays for certain operations.

Leave a Reply

Your email address will not be published. Required fields are marked *