For 2D arrays, hstack() places inputs side by side, requiring them to have the same number of rows, equivalent to np.concatenate(..., axis=1). For 1D arrays specifically, hstack() behaves like a simple end-to-end concatenation into a longer 1D array, since there's no second axis to stack along — this special-case behavior for 1D inputs is a common point of confusion, since it doesn't parallel vstack()'s behavior of promoting 1D arrays into rows.
1Understanding np.hstack()
For 2D arrays, hstack() places inputs side by side, requiring them to have the same number of rows, equivalent to np.concatenate(..., axis=1). For 1D arrays specifically, hstack() behaves like a simple end-to-end concatenation into a longer 1D array, since there's no second axis to stack along — this special-case behavior for 1D inputs is a common point of confusion, since it doesn't parallel vstack()'s behavior of promoting 1D arrays into rows.
Don't assume hstack() and vstack() are perfect mirror images for 1D inputs — vstack() turns two 1D arrays into a 2D result, stacked as rows, while hstack() on the same two 1D arrays just concatenates them into one longer 1D array.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.hstack((a, b)))2Practical Example
Here is a real-world application of np.hstack() showing how it is used in production NumPy code.
import numpy as np
a = np.array([[1], [2]])
b = np.array([[3], [4]])
print(np.hstack((a, b)))3Best Practices
Follow these guidelines when working with np.hstack():
1. Use hstack() for the common case of joining 2D arrays side by side by columns, instead of the more generic np.concatenate(..., axis=1)
2. Remember hstack() on 1D arrays produces a longer 1D array, not a 2D result, unlike the analogous vstack() call
3. Ensure every input array has the same number of rows, matching size along axis 0, before calling hstack() on 2D arrays
Tip: Don't assume hstack() and vstack() are perfect mirror images for 1D inputs — vstack() turns two 1D arrays into a 2D result, stacked as rows, while hstack() on the same two 1D arrays just concatenates them into one longer 1D array.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.hstack((a, b)))