PabloRdrRbl PabloRdrRbl - 4 months ago 4
Python Question

Create 3D array from a 2D array by replicating/repeating along the first axis

Suppose I have a

n × m
array, i.e.:

array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])


And I what to generate a 3D array
k × n × m
, where all the arrays in the new axis are equal, i.e.: the same array but now
3 × 3 × 3
.

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.]]])


How can I get it?

Answer

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.]]])
Comments