Concatenation
Concatenation joins arrays together. Think of it like merging PDFs or combining lists. The axis parameter controls how you join them.
Basic Concatenation
np.concatenate() joins arrays along an existing axis.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.concatenate((a, b))
print(f"Concatenated: {result}")
For 1D arrays, it just combines them end-to-end.
2D Concatenation
For 2D arrays, axis matters a lot.
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
row_concat = np.concatenate((a, b), axis=0)
col_concat = np.concatenate((a, b), axis=1)
print(f"Row concat (axis=0):\n{row_concat}")
print(f"Col concat (axis=1):\n{col_concat}")
axis=0 adds rows, axis=1 adds columns. The other dimensions must match.
Stacking Shortcut
np.stack() creates a new axis.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
stacked = np.stack((a, b))
print(f"Stacked:\n{stacked}")
print(f"Shape: {stacked.shape}")
Here is the thing - stack creates a new dimension, while concatenate uses an existing one.
One thing that confused me at first was when to use which. Use concatenate for existing axes, stack for new dimensions.
Try it Yourself →Key Takeaways
- np.concatenate() joins arrays along existing axes
- axis=0 adds rows, axis=1 adds columns
- np.stack() creates a new axis for stacking
- Other dimensions must match for concatenation