NumPy hstack()

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


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

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

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