[英]numpy.ufunc operation equivalent
I have 4D numpy
array a
and 3D array b
.我有 4D
numpy
数组a
和 3D 数组b
。 Also I have 2D arrays of indices i0
, j0
, k0
.我还有索引
i0
、 j0
、 k0
二维数组。 Suppose I want to use the following construction:假设我想使用以下结构:
np.add.at(a, (slice(None), k0, i0, j0), b)
As fas as I understood, a[slice(None), k0, i0, j0] += b
is not equivalent to this np.add.at
.据我
np.add.at
, a[slice(None), k0, i0, j0] += b
不等同于这个np.add.at
。 The question is how can this np.add.at
line can be replaced with a simple numpy
adding a[...] += b[...]
properly?问题是如何用简单的
numpy
添加a[...] += b[...]
来替换这个np.add.at
行?
You wrote that i0 , j0 and k0 are 2-D arrays.您写道i0 、 j0和k0是二维数组。
This is why I assumed that each row in these arrays defines a 3-D slice in b array (each array in the respective dimension).这就是为什么我假设这些数组中的每一行都在b数组中定义了一个 3-D 切片(每个数组在各自的维度中)。
For the test I defined these arrays as:对于测试,我将这些数组定义为:
k0 = np.array([[0,1],[1,2]])
i0 = np.array([[1,3],[2,4]])
j0 = np.array([[0,2],[2,4]])
so that the first 3-D slice from b is: b[0:1, 1:3, 0:2]
.所以b的第一个 3-D 切片是:
b[0:1, 1:3, 0:2]
。
Because k0 , i0 and j0 (taken "by row") define consecutive slices, you can not join them in a single instruction.因为k0 、 i0和j0 (“按行”)定义了连续的切片,所以不能在一条指令中加入它们。 My proposition is to perform your addition in the following loop:
我的提议是在以下循环中执行您的加法:
for sl in np.dstack([k0, i0, j0]):
idx = tuple(np.insert(np.r_[np.apply_along_axis(
lambda row: slice(*row), 0, sl)], 0, slice(None)))
a[tuple(idx)] += b[tuple(idx[1:])]
idx is a 4-tuple to index array " a ". idx是一个 4 元组,用于索引数组“ a ”。 The first element is slice(None) - operate on all elements in the first dimension.
第一个元素是slice(None) - 对第一维中的所有元素进行操作。 Following elements are slices for following dimensions.
以下元素是以下维度的切片。
To index b array the same idx is used, but without the first element.要索引b数组,使用相同的idx ,但没有第一个元素。
To test the above code, I defined both arrays as:为了测试上面的代码,我将两个数组定义为:
aDim = (2, 2, 4, 4)
bDim = aDim[1:]
a = np.arange(1, np.array(aDim).prod() + 1).reshape(aDim)
b = np.arange(501, np.array(bDim).prod() + 501).reshape(bDim)
(print them to see the initial content). (打印它们以查看初始内容)。
After my code was executed, a contains:执行我的代码后, a包含:
array([[[[ 1, 2, 3, 4],
[510, 512, 7, 8],
[518, 520, 11, 12],
[ 13, 14, 15, 16]],
[[ 17, 18, 19, 20],
[ 21, 22, 23, 24],
[ 25, 26, 554, 556],
[ 29, 30, 562, 564]]],
[[[ 33, 34, 35, 36],
[542, 544, 39, 40],
[550, 552, 43, 44],
[ 45, 46, 47, 48]],
[[ 49, 50, 51, 52],
[ 53, 54, 55, 56],
[ 57, 58, 586, 588],
[ 61, 62, 594, 596]]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.