What is the numpy.hstack() function in NumPy?

Overview

The hstack() function in NumPy is used to stack or arrange arrays in sequence horizontally (column-wise).

Syntax

numpy.hstack(tup)
Syntax for the hstack() function in NumPy

Parameter value

The hstack() function takes a single parameter value, tup, which represents the arrays that have the same shape along all the axes, except for the first axis.

Return value

The hstack() function returns an array formed by stacking the given arrays horizontally.

Example

import numpy as np
# creating input arrays
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
# stacking the arrays horizontally
stacked_array = np.hstack((a, b))
# printing the new array
print(stacked_array)

Example

  • Line 1: We import the numpy module.
  • Lines 3–4: We create input arrays, a and b, using the array() function.
  • Line 7: We horizontally stack arrays a and b using the hstack() function. The result is assigned to a variable, stacked_array.
  • Line 10: We print the newly stacked array, stacked_array.

Free Resources