Introduce a new axis at the start with None/np.newaxis
and replicate along it with np.repeat
. This should work for extending any n
dim array to n+1
dim array. The implementation would be -
np.repeat(arr[None,...],k,axis=0)
Sample run -
In [143]: arr
Out[143]:
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
In [144]: np.repeat(arr[None,...],3,axis=0)
Out[144]:
array([[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]],
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]],
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]]])
View-output
for memory-efficiency
We can also generate a 3D
view and achieve virtually free runtime with np.broadcast_to
. More info - here
. Hence, simply do -
np.broadcast_to(arr,(3,)+arr.shape) # repeat 3 times