例如:
我有一个大型数组,一个1000×1000和一个小数组B 10×10我希望B中的每个元素响应数组B中的100×100个元素.不需要任何插值,只需在B中使用相同的元素进行所有10000个 *** 作一个.
我可以调整两个数组的大小,使A的形状是B的倍数.通常它们在所有维度中都是1:10000或1:1000.数组表示具有不同分辨率但相同范围的数据样本.
我知道我可以对阵列B进行过采样,例如通过使用Kronecker产品,但将数组B保持在较小状态会更好,特别是因为我的一些数组在处理和存储方面变得非常大.我正在使用xarray和dask,但任何numpy *** 作也会起作用.
我希望这段代码解释了我想要做的事情:
import numpy as npA = 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) + BC = np.repeat(np.repeat(A,res,axis=0),axis=1)+B
我有一种感觉,这个问题一定是以前一直存在,但我找不到任何适用于这种特殊情况的答案.
解决方法 通过广播,我们可以“复制”一个小阵列,以便与更大的阵列一起工作.例如,如果a = np.random.rand(10)b = np.random.rand(1000).reshape(10,100)a[:,None]+b
这里的技巧是将A的每个元素与B的(100,100)块配对.为此,我们需要重新整形和转置.
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,axis=1)+BIn [5]: C.shapeOut[5]: (1000,1000)
将B划分为这些(100,100)个块:
In [7]: B1 = B.reshape(10,100,10,100).transpose(0,2,1,3)In [8]: B1.shapeOut[8]: (10,100)
现在我们可以添加广播
In [9]: C1 = B1 + A[:,:,None,None]In [10]: C1.shapeOut[10]: (10,100)
重塑为原始B形状:
In [11]: C1=C1.transpose(0,3).reshape(B.shape)
他们匹配:
In [12]: np.allclose(C,C1)Out[12]: True总结
以上是内存溢出为你收集整理的python – 不同大小的数组的元素 *** 作全部内容,希望文章能够帮你解决python – 不同大小的数组的元素 *** 作所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)