1

I have the following 1D numpy array:

li = array([ 0.002,  0.003,  0.005,  0.009])

li.shape
(4L,)

I would like to make a 2D numpy array (li_2d) with shape of (4L,5L) that looks like this:

li_2d = array([[  0.002,   0.002,   0.002,  0.002,  0.002],
               [  0.003,   0.003,   0.003,  0.003,  0.003],
               [  0.005,   0.005,   0.005,  0.005,  0.005]
               [  0.009,   0.009,   0.009,  0.009,  0.009]])

Is there some numpy function to do that? Thank you

diegus
  • 1,168
  • 2
  • 26
  • 57
  • 2
    I think there's probably a duplicate somewhere but I'm not sure that's the right one (e.g. the duplicate will show how to use `tile` or `repeat`). – Alex Riley Dec 08 '15 at 15:37
  • 3
    Yep, I was too quick. Here's the correct one: http://stackoverflow.com/questions/1550130/cloning-row-or-column-vectors – Mel Dec 08 '15 at 15:44

3 Answers3

2

You can get the desired shape using numpy.tile:

li = np.array([ 0.002,  0.003,  0.005,  0.009])
np.tile(li.reshape(4, 1), (1, 5))

array([[ 0.002,  0.002,  0.002,  0.002,  0.002],
       [ 0.003,  0.003,  0.003,  0.003,  0.003],
       [ 0.005,  0.005,  0.005,  0.005,  0.005],
       [ 0.009,  0.009,  0.009,  0.009,  0.009]])
Scott
  • 6,089
  • 4
  • 34
  • 51
0

You can do this with np.pad. First, reshape your array to a shape of (4,1), then pad 4 columns on the edge:

In [18]: np.pad(li.reshape(4,1),((0,0),(0,4)),mode='edge')
Out[18]: 
array([[ 0.002,  0.002,  0.002,  0.002,  0.002],
       [ 0.003,  0.003,  0.003,  0.003,  0.003],
       [ 0.005,  0.005,  0.005,  0.005,  0.005],
       [ 0.009,  0.009,  0.009,  0.009,  0.009]])
tmdavison
  • 64,360
  • 12
  • 187
  • 165
0

You can also do this with numpy.repeat:

In [5]: np.repeat(li, 5).reshape(li.shape[0], 5)
Out[5]: 
array([[ 0.002,  0.002,  0.002,  0.002,  0.002],
       [ 0.003,  0.003,  0.003,  0.003,  0.003],
       [ 0.005,  0.005,  0.005,  0.005,  0.005],
       [ 0.009,  0.009,  0.009,  0.009,  0.009]])

You can get the transpose by either using numpy.tile or the transpose operator:

In [8]: np.tile(li, 5).reshape(5, li.shape[0])
Out[8]: 
array([[ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009]])

In [9]: np.repeat(li, 5).reshape(li.shape[0], 5).T
Out[9]: 
array([[ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009],
       [ 0.002,  0.003,  0.005,  0.009]])
wflynny
  • 18,065
  • 5
  • 46
  • 67