【发布时间】:2014-12-02 14:37:19
【问题描述】:
我正在使用 numpy 1.9 和 python 2.7.5 处理 3 维矩阵。 这是一个例子:
>>> A
array([[[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]],
[[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]]])
>>> B
array([[[-1., -1., -1.],
[99., 100., 101.],
[-1., -1., -1.],
[-1., -1., -1.],
[-1., -1., -1.]],
[[-1., -1., -1.],
[-1., -1., -1.],
[102., 103., 104.],
[-1., -1., -1.],
[-1., -1., -1.]]])
>>> C
array([1, 2])
根据 C,我想在 A 中插入 B 中的所有元素。
示例:c[0] = 1 => After A[0, 1, :] has to be inserted B[0, 1, :]
这是预期结果的示例
>>> D
array([[[1., 1., 1.],
[1., 1., 1.],
[99., 100., 101.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[102., 103., 104.]
[1., 1., 1.],
[1., 1., 1.]]])
我发现this stackoverflow question 与我的非常相似,只是该解决方案仅适用于二维矩阵,而我正在使用 3 维。
这是我的解决方案,但结果不正确:
C2 = np.repeat(C, 3)
r1 = np.repeat(np.arange(A.shape[0]), 3)
r2 = np.tile(np.arange(3), A.shape[0])
index_map = np.ravel_multi_index((r1, C2, r2), A.shape) + 1
np.insert(A.ravel(), index_map, B.ravel()[index_map]).reshape(A.shape[0], A.shape[1] + 1, A.shape[2])
这是一个使用 for 循环的正确但缓慢的解决方案:
A_2 = np.zeros((A.shape[0], A.shape[1] + 1, A.shape[2]))
for j in xrange(np.size(C, 0)):
i = C[j]
A_2[j, :, :] = np.concatenate((A[j, 0:i + 1, :], [B[j, i, :]], A[j, i + 1:, :]))
有什么想法吗?
谢谢!
【问题讨论】:
-
“我得到了不好的结果”是什么意思?不正确?正确但太慢?
-
@WarrenWeckesser 我得到了不正确的结果,因为我将结果与使用 for 循环获得的正确结果进行比较。现在我编辑我的答案,发布正确的 for 循环
-
我建议实际显示所需的结果和不正确的结果——也许使用更小的数组(比如 4x3x2)。
-
您的 for 循环示例对我来说失败了,因为 concatenate 给出了 6 行,但 A2 只需要 5 行。那是怎么回事?它真的像你上面写的那样在你的系统上工作吗?
-
现在我得到
IndexError: index 3 is out of bounds for axis 0 with size 3的例子。
标签: python performance numpy matrix multidimensional-array