Open In App

numpy.hstack() in Python

Last Updated : 12 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
15 Likes
Like
Report

numpy.hstack() function stacks arrays in sequence horizontally (column-wise). It joins arrays along their second axis for 2D arrays or flattens and joins them for 1D arrays. This is useful for combining arrays side by side.

Example:


Output
[1 2 3 4 5 6]

Arrays a and b are horizontally stacked to form one combined 1D array.

Syntax

numpy.hstack(tup, *, dtype=None, casting='same_kind')

Parameters:

Parameter

Type

Description

tup

sequence of array_like

Arrays to stack horizontally (must match in all but the second axis).

dtype

data-type, optional

Desired data type of the result array.

casting

{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional

Controls data casting (default: 'same_kind').

Returns: This function returns horizontally stacked array of the input arrays.

Examples

Example 1: Horizontal stacking of 2D arrays


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

Each row of a and b is concatenated horizontally to form a wider 2D array.

Example 2: Stacking arrays of different shapes (raises an error)

Output

ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 0, the array a...

Arrays must be compatible in shape except along the concatenation axis.

Example 3: Horizontal stacking with negative numbers


Output
[-1 -2 -3  4  5  6]

Works with negative integers too. The resulting array preserves the sign of the original numbers.


Next Article
Practice Tags :

Similar Reads