2014-01-31 65 views
1

兩個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

回答

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使代碼更清潔。

+0

太棒了!如何計時? –

+0

@ Jean-Pat更新 – zhangxaochen