Boosting Performance: Repeating 2D Arrays in Python with NumPy
Problem:
You want to take a 2D array (matrix) and create a new 3D array where the original 2D array is repeated N times along a specified axis. This is useful in various machine learning and image processing tasks where you need to create stacked or batched versions of data.
Solution using NumPy:
NumPy provides several efficient ways to achieve this:
Method 1: Using np.repeat
- Reshape the input array:
- Repeat along the desired axis:
- Use
np.repeat
to repeat the reshaped arrayN
times along the first axis (axis=0).
- Use
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
N = 3
# Reshape and repeat
repeated_arr = np.repeat(np.expand_dims(arr, axis=0), N, axis=0)
print(repeated_arr)
This will output:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
Method 2: Using list comprehension or generator expression
- Create a list or generator expression that expands the 2D array
N
times. - Convert the list or generator expression to a NumPy array.
repeated_arr = np.array([arr] * N)
python arrays numpy