2012-06-17 67 views
4

份可以說我有一個陣列numpy的,映射一個陣列到另一個

a = numpy.arange(8*6*3).reshape((8, 6, 3)) 
    #and another: 
    l = numpy.array([[0,0],[0,1],[1,1]]) #an array of indexes to array "a" 
    #and yet another: 
    b = numpy.array([[0,0,5],[0,1,0],[1,1,3]]) 

其中「L」和「b」的長度相等, ,我想說

a[l] = b 

這樣一個[0] [0]變成[0,0,5],a [0] [1]變成[0,1,0]等

它似乎工作正常時,維數組,但它給我的錯誤

ValueError: array is not broadcastable to correct shape 

當我嘗試將其與3維陣列。

回答

3
import numpy as np 

a = np.arange(8*6*3).reshape((8, 6, 3)) 
l = np.array([[0,0],[0,1],[1,1]]) #an array of indexes to array "a" 
b = np.array([[0,0,5],[0,1,0],[1,1,3]]) 

a[tuple(l.T)] = b 
print(a[0,0]) 
# [0 0 5] 

print(a[0,1]) 
# [0 1 0] 

print(a[1,1]) 
# [1 1 3] 

Anne Archibald says

When you are supplying arrays in all index slots, what you get back has the same shape as the arrays you put in; so if you supply one-dimensional lists, like

A[[1,2,3],[1,4,5],[7,6,2]]

what you get is

[A[1,1,7], A[2,4,6], A[3,5,2]]

當你比較,與你的榜樣,您會看到

a[l] = b告訴NumPy的設置

a[0,0,1] = [0,0,5] 
a[0,1,1] = [0,1,0] 

和葉b第三個元素未分配。這就是爲什麼你的錯誤

ValueError: array is not broadcastable to correct shape 

的解決方案是將數組l轉成正確的形狀:

In [50]: tuple(l.T) 
Out[50]: (array([0, 0, 1]), array([0, 1, 1])) 

(你也可以使用zip(*l),但tuple(l.T)是有點快。)

+0

以 「一[郵編(* 1)]」 我得到這個錯誤:回溯(最近通話最後一個): 文件 「C:/Python32/test.py」,7號線,在 一個[郵編(* L )] = b IndexError:索引必須是一個整數或序列 –

+0

感謝,用「元組(LT)」它的工作原理;) –

0

或與您相同的陣列可以使用

for i in range(len(l)): 
    a[l[i][0]][l[i][1]]=b[i] 
相關問題