我有以下1D numpy数组:
li = array([ 0.002, 0.003, 0.005, 0.009])
li.shape
(4L,)
我想制作一个形状为(4L,5L)的2D numpy数组(li_2d),如下所示:
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]])
是否有一些numpy功能呢? 谢谢
答案 0 :(得分:1)
您可以使用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]])
答案 1 :(得分:0)
您可以使用np.pad
执行此操作。首先,将数组重塑为(4,1)
形状,然后在边缘填充4列:
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]])
答案 2 :(得分:0)
您也可以使用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]])
您可以使用numpy.tile
或转置运算符来获得转置:
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]])