我正在使用3維矩陣使用numpy 1.9和python 2.7.5。 下面是一個例子:在numpy中插入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])
我想從B A的所有元素插入,根據C. 實施例: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,它與我的真的很相似,只是解決方案只適用於二維矩陣,而我正在使用三維。
這裏是我的解決辦法,但我得到不正確的結果:
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:, :]))
任何想法?
謝謝!
什麼是「我很糟糕的結果」是什麼意思?不正確的?正確但太慢? – 2014-10-08 03:03:14
@WarrenWeckesser我獲得了不正確的結果,因爲我將結果與for循環獲得的結果進行了比較。現在我編輯我的答案張貼正確的循環 – Rowandish 2014-10-08 03:06:23
我會建議實際顯示所需的結果和不正確的結果 - 也許與較小的數組(例如4x3x2)。 – senderle 2014-10-08 03:10:01