w3resource

NumPy: numpy.hstack() function

numpy.hstack() function

The numpy.hstack() function is used to stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis. Rebuilds arrays divided by hsplit.
This function is useful in the scenarios when we have to concatenate two arrays of different shapes along the second axis (column-wise). For example, to combine two arrays of shape (n, m) and (n, l) to form an array of shape (n, m+l).

Syntax:

numpy.hstack(tup)
NumPy manipulation: hstack() function

Parameter:

Name Description Required /
Optional
tup The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length. Required

Return value:

stacked : ndarray The array formed by stacking the given arrays.

Example: Horizontally stack numpy arrays using numpy.hstack()

>>> import numpy as np
>>> x = np.array((3,5,7))
>>> y = np.array((5,7,9))
>>> np.hstack((x,y))
array([3, 5, 7, 5, 7, 9])

In the above code there are two one-dimensional numpy arrays 'x' and 'y' with three elements each. By applying np.hstack((x,y)), we get a new one-dimensional numpy array that has all the elements of x and y stacked horizontally. The resulting numpy array has six elements in total.
np.hstack() is useful when we want to combine multiple numpy arrays horizontally. It can be used to concatenate multiple numpy arrays with the same number of rows, but different number of columns, into a single numpy array.

Pictorial Presentation:

NumPy manipulation: hstack() function

Example: Horizontal stacking of numpy arrays

>>> import numpy as np
>>> x = np.array([[3], [5], [7]])
>>> y = np.array([[5], [7], [9]])
>>> np.hstack((x,y))
array([[3, 5],
       [5, 7],
       [7, 9]])

The above code uses the numpy.hstack() function to horizontally stack two numpy arrays. The first array x is a column vector of shape (3,1) and the second array y is also a column vector of the same shape.
The numpy.hstack() function stacks the two arrays horizontally to produce a new 2-dimensional array of shape (3,2) where the elements of the first array appear in the first column and the elements of the second array appear in the second column.
The resulting array contains the elements [3, 5] in the first row, [5, 7] in the second row, and [7, 9] in the third row.

Pictorial Presentation:

NumPy manipulation: hstack() function

Python - NumPy Code Editor:

Previous: dstack()
Next: vstack()



Follow us on Facebook and Twitter for latest update.