Elena Popa
Elena Popa

Reputation: 357

fill a 2D array using a for loop using other 2D arrays

I have two 2D numpy arrays a(N,D) b(M,D) and I want to fill a third array c(M,D*N) which is a function of a and b. If N= 2 and D=3 I want c to be the following:

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] 

How can I fill c using a loop (for, while)?

Upvotes: 1

Views: 31

Answers (1)

Divakar
Divakar

Reputation: 221574

Here's a vectorized way leveraging broadcasting, meant for performance efficiency -

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

Sample run -

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]])

Upvotes: 1

Related Questions