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:
Pythonimportnumpyasnpa=np.array([1,2,3])b=np.array([4,5,6])res=np.hstack((a,b))print(res)
Arraysaandb 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
Pythonimportnumpyasnpa=np.array([[1,2],[3,4]])b=np.array([[5,6],[7,8]])res=np.hstack((a,b))print(res)
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)
Pythonimportnumpyasnpa=np.array([[1,2]])b=np.array([[3,4],[5,6]])res=np.hstack((a,b))
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
Pythonimportnumpyasnpa=np.array([-1,-2,-3])b=np.array([4,5,6])res=np.hstack((a,b))print(res)
Works with negative integers too. The resulting array preserves the sign of the original numbers.