NumPy hstack()

The hstack() method stacks the sequence of input arrays horizontally.

Example

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])

# stack the arrays stackedArray = np.hstack((array1, array2))
print(stackedArray) ''' Output [[0 1 4 5] [2 3 6 7]] '''

hstack() Syntax

The syntax of hstack() is:

numpy.hstack(tup)

hstack() Argument

The hstack() method takes a single argument:

  • tup - a tuple of arrays to be stacked

Note: The shape of all arrays in a given tuple must be the same, except for the second dimension because we are stacking in axis 1 (horizontally).


hstack() Return Value

The hstack() method returns the horizontally stacked array.


Example 1: Horizontally Stack 3 Arrays

import numpy as np

# arrays with shape (2,2)
array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])

# array with shape (2, 1)
array3 = np.array([[8], [9]])

# stack the arrays stackedArray = np.hstack((array1, array2, array3))
print(stackedArray)

Output

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

Here, we have stacked 3 arrays of different shapes.

The shape of array3 is (2,1), yet we could stack it with arrays of shape (2, 2) because only the second dimension (2, 1) of array3 is different from the other 2 arrays.


Example 2: Horizontally Stack Arrays With Invalid Shapes

import numpy as np

# arrays with shape (2, 2)
array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])

# arrays with shape (1, 2)
array3 = np.array([[8, 9]])

# stack the arrays with invalid shape stackedArray = np.hstack((array1, array2, array3))
print(stackedArray)

Output

ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 2 has size 1

Here, the shape of array3 is (1, 2), which conflicts while stacking with arrays of shape (2,2).

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges