# python – 不同大小的数组的元素操作

pythonic的方式来执行不同大小的数组的元素操作而不过度采样较小的数组？

``````import numpy as np

A = np.random.rand(10,10)
B = np.random.rand(1000,1000)

res = np.shape(B)[0]//np.shape(A)[0]

#I want to add A and B so that each element in A is added to 100x100 elements in B.
#This doesn't work of obvious reasons:
#C = A+B

#This solution sacrifices the resolution of B:
C = A+B[::res,::res]

#These solutions creates an unnecessary large array for the operation(don't they?):
K = np.ones((res,res))
C = np.kron(A, K) + B

C = np.repeat(np.repeat(A,res, axis=0), res, axis=1)+B
``````

``````a = np.random.rand(10)
b = np.random.rand(1000).reshape(10,100)
a[:,None]+b
``````

``````In [3]: A = np.random.rand(10,10)
...: B = np.random.rand(1000,1000)
...: res = np.shape(B)[0]//np.shape(A)[0]
``````

``````In [4]: K = np.ones((res,res))
...: C = np.kron(A, K) + B
...:
...: C = np.repeat(np.repeat(A,res, axis=0), res, axis=1)+B

In [5]: C.shape
Out[5]: (1000, 1000)
``````

``````In [7]: B1 = B.reshape(10,100,10,100).transpose(0,2,1,3)

In [8]: B1.shape
Out[8]: (10, 10, 100, 100)
``````

``````In [9]: C1 = B1 + A[:,:,None,None]

In [10]: C1.shape
Out[10]: (10, 10, 100, 100)
``````

``````In [11]: C1=C1.transpose(0,2,1,3).reshape(B.shape)
``````

``````In [12]: np.allclose(C,C1)
Out[12]: True
``````
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。