0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.hstack in NumPy: Simple Guide and Examples

Use np.hstack to join arrays horizontally (side by side) along their second axis. It takes a tuple or list of arrays with the same number of rows and returns a new array with columns combined.
๐Ÿ“

Syntax

The basic syntax of np.hstack is:

  • np.hstack(tup): where tup is a tuple or list of arrays to join.
  • The arrays must have the same number of rows (first dimension).
  • The function stacks arrays horizontally (column-wise) to create a wider array.
python
np.hstack(tup)
๐Ÿ’ป

Example

This example shows how to horizontally stack two 2D arrays with the same number of rows.

python
import numpy as np

# Define two arrays with 2 rows each
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])

# Stack arrays horizontally
result = np.hstack((arr1, arr2))
print(result)
Output
[[1 2 5 6] [3 4 7 8]]
โš ๏ธ

Common Pitfalls

Common mistakes when using np.hstack include:

  • Trying to stack arrays with different numbers of rows causes an error.
  • Passing arrays as separate arguments instead of a tuple or list.
  • Confusing hstack with vstack which stacks vertically (row-wise).
python
import numpy as np

# Wrong: arrays have different row counts
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6]])

try:
    np.hstack((arr1, arr2))
except ValueError as e:
    print(f"Error: {e}")

# Correct: arrays have same row count
arr3 = np.array([[5, 6], [7, 8]])
result = np.hstack([arr1, arr3])
print(result)
Output
Error: all the input arrays must have same number of rows [[1 2 5 6] [3 4 7 8]]
๐Ÿ“Š

Quick Reference

ParameterDescription
tupTuple or list of arrays to stack horizontally
ReturnNew array with input arrays stacked side by side
RequirementAll arrays must have the same number of rows
AxisStacks arrays along axis=1 (columns)
โœ…

Key Takeaways

Use np.hstack to join arrays side by side along columns.
Input arrays must have the same number of rows.
Pass arrays as a tuple or list to np.hstack.
np.hstack stacks horizontally; use np.vstack for vertical stacking.
Mismatched dimensions cause errors when using np.hstack.