0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.concatenate in NumPy: Syntax and Examples

Use np.concatenate to join two or more arrays along an existing axis by passing a tuple of arrays and specifying the axis. It combines arrays without copying data unnecessarily, making it efficient for array merging.
๐Ÿ“

Syntax

The basic syntax of np.concatenate is:

  • arrays: A tuple or list of arrays to join.
  • axis: The axis along which to concatenate (default is 0).
  • out: Optional output array to place the result.
python
np.concatenate((array1, array2, ...), axis=0, out=None)
๐Ÿ’ป

Example

This example shows how to join two 2D arrays along rows (axis=0) and columns (axis=1).

python
import numpy as np

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

# Concatenate along rows (axis=0)
concat_axis0 = np.concatenate((arr1, arr2), axis=0)

# Concatenate along columns (axis=1)
concat_axis1 = np.concatenate((arr1, arr2), axis=1)

print('Concatenate along axis=0:')
print(concat_axis0)
print('\nConcatenate along axis=1:')
print(concat_axis1)
Output
Concatenate along axis=0: [[1 2] [3 4] [5 6] [7 8]] Concatenate along axis=1: [[1 2 5 6] [3 4 7 8]]
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Trying to concatenate arrays with incompatible shapes along the chosen axis.
  • Forgetting to pass arrays as a tuple or list.
  • Using axis values outside the valid range.

Always check array shapes before concatenation.

python
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([[4, 5, 6]])

# Wrong: shapes incompatible along axis=0
# np.concatenate((arr1, arr2), axis=0)  # This will raise an error

# Right: flatten arr2 or adjust shapes
arr2_flat = arr2.flatten()
result = np.concatenate((arr1, arr2_flat), axis=0)
print(result)
Output
[1 2 3 4 5 6]
๐Ÿ“Š

Quick Reference

Remember these tips when using np.concatenate:

  • Input arrays must have the same shape except in the concatenation axis.
  • Use axis=0 to stack vertically (rows).
  • Use axis=1 to stack horizontally (columns) for 2D arrays.
  • Pass arrays as a tuple or list.
โœ…

Key Takeaways

Use np.concatenate to join arrays along an existing axis by passing them as a tuple or list.
Ensure arrays have compatible shapes except along the concatenation axis to avoid errors.
Specify the axis parameter to control the direction of concatenation (default is 0).
Pass arrays as a tuple or list; passing separate arguments will cause an error.
Check array shapes before concatenation to prevent shape mismatch errors.