Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding NumPy array over extra dimension

Tags:

python

numpy

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)
like image 461
astrojuanlu Avatar asked Jul 10 '13 20:07

astrojuanlu


1 Answers

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.]]])
like image 145
Daniel Avatar answered Nov 11 '22 03:11

Daniel