Skip to main content
 首页 » 编程设计

python之在不枚举数组的情况下创建 Numpy 数组

2025年05月04日9qq号

从这里开始:

x = range(30,60,2)[::-1]; 
x = np.asarray(x); x 
 
array([58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30]) 

像这样创建一个数组:(注意,第一项重复)但是如果我可以在不重复第一项的情况下更快地完成此操作,我可以 np.hstack 第一项。

[[58 58 56 54 52] 
 [56 56 54 52 50] 
 [54 54 52 50 48] 
 [52 52 50 48 46] 
 [50 50 48 46 44] 
 [48 48 46 44 42] 
 [46 46 44 42 40] 
 [44 44 42 40 38] 
 [42 42 40 38 36] 
 [40 40 38 36 34] 
 [38 38 36 34 32] 
 [36 36 34 32 30] 
 [34 34 32 30 None] 
 [32 32 30 None None] 
 [30 30 None None None]] 

下面的代码有效,希望它在没有“for”循环和枚举的情况下更快。

arr = np.empty((0,5), int) 
 
for i,e in enumerate(x): 
    arr2 = np.hstack((x[i], x[i:i+4], np.asarray([None]*5)))[:5] 
    arr  = np.vstack((arr,arr2)) 

请您参考如下方法:

方法 #1

这是使用 NumPy broadcasting 的矢量化方法-

N = 4 # width factor 
x_ext = np.concatenate((x,[None]*(N-1))) 
arr2D = x_ext[np.arange(N) + np.arange(x_ext.size-N+1)[:,None]] 
out = np.column_stack((x,arr2D)) 

方法 #2

这是另一个使用 hankel 的-

from scipy.linalg import hankel 
 
N = 4 # width factor 
x_ext = np.concatenate((x,[None]*(N-1))) 
out = np.column_stack((x,hankel(x_ext[:4], x_ext[3:]).T)) 

运行时测试

这是 @Aaron's benchmarking script 的修改版本为这篇文章使用与他在该脚本中的文章相同的输入格式以进行公平的基准测试并仅关注这两种方法 -

upper_limit = 58 # We will edit this to vary the dataset sizes 
 
print "Timings are : " 
t = time() 
for _ in range(1000):  #1000 iterations of @Aaron's soln. 
    width = 3 
    x = np.array(range(upper_limit,28,-2) + [float('nan')]*width) 
    arr = np.empty([len(x)-width, width+2]) 
    arr[:,0] = x[:len(x)-width] 
    for i in xrange(len(x)-width):  
        arr[i,1:] = x[i:i+width+1] 
print(time()-t) 
 
t = time() 
for _ in range(1000):  
    N = 4 # width factor 
    x_ext = np.array(range(upper_limit,28,-2) + [float('nan')]*(N-1)) 
    arr2D = x_ext[np.arange(N) + np.arange(x_ext.size-N+1)[:,None]] 
    out = np.column_stack((x_ext[:len(x_ext)-N+1],arr2D)) 
print(time()-t) 

案例#1(upper_limit = 58):

Timings are :  
0.0316879749298 
0.0322730541229 

案例#2(upper_limit = 1058):

Timings are :  
0.680443048477 
0.124517917633 

案例 #3(upper_limit = 5058):

Timings are :  
3.28129291534 
0.47504901886