使用其他2D数组的for循环填充2D数组

时间:2019-05-31 09:03:45

标签: python-3.x loops numpy indexing

我有两个2D numpy数组a(N,D)b(M,D),我想填充第三个数组c(M,D * N),这是a和b的函数。如果N = 2和D = 3,我希望c为以下:

c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]    
c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2] 

c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1] 
c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2] 

如何使用循环(一段时间)填充c?

1 个答案:

答案 0 :(得分:1)

这是利用broadcasting的矢量化方式,旨在提高性能-

bs = b*np.std(b,axis=0,keepdims=True)
c_out = (bs[:,None,:]+a).reshape(len(b),-1)

样品运行-

In [43]: N,M,D = 2,4,3
    ...: np.random.seed(0)
    ...: a = np.random.rand(N,D)
    ...: b = np.random.rand(M,D)
    ...: c = np.zeros((M,D*N))
    ...: 
    ...: c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
    ...: c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]    
    ...: c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2] 
    ...: 
    ...: c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
    ...: c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1] 
    ...: c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2]

In [44]: c
Out[44]: 
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])

In [45]: bs = b*np.std(b,axis=0,keepdims=True)
    ...: c_out = (bs[:,None,:]+a).reshape(len(b),-1)

In [46]: c_out
Out[46]: 
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])
相关问题