Expanding NumPy array over extra dimension

numpy, python

Solution

I would recommend np.tile.

>>> a=np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> np.tile(a,(6,1))
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])

>>> b= np.eye(2)
>>> b
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> np.tile(b,(3,1,1))
array([[[ 1.,  0.],
        [ 0.,  1.]],

       [[ 1.,  0.],
        [ 0.,  1.]],

       [[ 1.,  0.],
        [ 0.,  1.]]])

Expanding in many dimensions is pretty easy also:

>>> np.tile(b,(2,2,2))
array([[[ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.],
        [ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.]],

       [[ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.],
        [ 1.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.]]])

Problem

What is the easiest way to expand a given NumPy array over an extra dimension? For example, suppose I have ``` >>> np.arange(4) array([0, 1, 2, 3]) >>> _.shape (4,) >>> expand(np.arange(4), 0, 6) array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) >>> _.shape (6, 4) ``` or this one, a bit more complicated: ``` >>> np.eye(2) array([[ 1., 0.], [ 0., 1.]]) >>> _.shape (2, 2) >>> expand(np.eye(2), 0, 3) array([[[ 1., 0.], [ 0., 1.]], [[ 1., 0.], [ 0., 1.]], [[ 1., 0.], [ 0., 1.]]]) >>> _.shape (3, 2, 2) ```

Original source