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): wheretupis 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
hstackwithvstackwhich 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
| Parameter | Description |
|---|---|
| tup | Tuple or list of arrays to stack horizontally |
| Return | New array with input arrays stacked side by side |
| Requirement | All arrays must have the same number of rows |
| Axis | Stacks 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.