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

什么是最快和最
pythonic的方式来执行不同大小的数组的元素操作而不过度采样较小的数组?

例如:
我有一个大型数组,一个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 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

这里的技巧是将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,res, axis=0), res, axis=1)+B

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

将B划分为这些(100,100)个块:

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)

重塑为原始B形状:

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

他们匹配:

In [12]: np.allclose(C,C1)
Out[12]: True
点赞