如何使用带矢量化代码的渐变填充numpy数组?

时间:2014-01-31 14:41:57

标签: python arrays numpy

必须按如下方式填写两个numpy数组:

[0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]]

[[0 0 0]
 [1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]]

enter image description here

第一个想法是:

ax=np.zeros((5,3),np.int16)
ay=np.zeros((5,3),np.int16)

for j in range(0,3):
    for i in range(0,5):
        ax[i,j]=j#filling ax with x=col
        ay[i,j]=i#filling ay with y values y=li

第二个想法是:

bx = np.zeros((5,3),np.int16)
by = np.zeros((5,3),np.int16)

for j in range(3):
    bx[:,j]=j

for i in range(5):
    by[i,:]=i

我确信有更好的方法,哪一个? 谢谢 JP

1 个答案:

答案 0 :(得分:2)

我认为使用numpy.tile可能会更好:

In [422]: np.tile((0,1,2), (5,1))
Out[422]: 
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2]])

In [473]: tile(arange(5)[:,None], 3)
Out[473]: 
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])

时间效率:

对于一个小的形状矩阵(5,3),for循环更快:

In [490]: timeit np.tile((0,1,2), (5,1))
10000 loops, best of 3: 38.3 us per loop

In [491]: %%timeit
     ...: bx = np.zeros((5,3),np.int16)
     ...: for j in range(3):
     ...:     bx[:,j]=j
     ...: 
100000 loops, best of 3: 16.5 us per loop

但是对于大的形状矩阵(5,1000),tile更快:

In [488]: timeit n=1000; tile(xrange(n), (5,1))
1000 loops, best of 3: 313 us per loop

In [489]: %%timeit
     ...: n=1000
     ...: bx=zeros((5, n))
     ...: for j in range(n):
     ...:     bx[:,j]=j
     ...: 
100 loops, best of 3: 3.97 ms per loop

无论如何,tile使代码更清晰。