2017-07-26 57 views
0

這是我的numpy的陣列的一個例子,我想應用一個函數mapping爲的每行矩陣testnumpy的錯誤沿軸線應用「ValueError異常:無法廣播從形狀(2)輸入數組的形狀(1)」

test = np.array([[0, .1, .9], [.1, .9, .8], [.8, .6, .1]]) 
test2 = np.array(['a','b','c']) 

def mapping(x): 
    return test2[np.where(x > .7)].tolist() 

這個作品

mapping(test[0]), mapping(test[1]), mapping(test[2]) 

正確的結果:(['c'], ['b', 'c'], ['a','b'])

但這不和吐出的錯誤。

np.apply_along_axis(mapping, 1, test) 

我不明白爲什麼會出現這種情況。請幫忙。

+1

'apply_along_axis'是試圖從結果中創建一個規則數組。但是你的行生成了1個或2個元素的列表組合。你爲什麼試圖使用這個功能?不是對行進行簡單的迭代嗎? – hpaulj

回答

1

apply文檔:

The output array. The shape of `outarr` is identical to the shape of 
`arr`, except along the `axis` dimension. This axis is removed, and 
replaced with new dimensions equal to the shape of the return value 
of `func1d`. So if `func1d` returns a scalar `outarr` will have one 
fewer dimensions than `arr`. 

什麼是mapping返回值的形狀? apply...嘗試通過使用第一項進行計算來猜測這一點。在你的情況下['c']。所以它試圖返回一個(3,1)數組,並在第二行返回值時遇到問題。

給你的函數適用於test行的最好方法是:

In [240]: [mapping(x) for x in test] 
Out[240]: [['c'], ['b', 'c'], ['a']] 

In [246]: np.apply_along_axis(mapping, 1, test[[0,2],:]) 
Out[246]: 
array([['c'], 
     ['a']], 
     dtype='<U1') 

即使它的工作原理,apply_along_axis不會提高速度 - 事實上,它更糟糕的是

In [249]: timeit [mapping(x) for x in test] 
20.4 µs ± 33 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 
In [250]: timeit np.array([mapping(x) for x in test]) 
25.1 µs ± 192 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) 
In [251]: timeit np.apply_along_axis(mapping, 1, test[[0,2,2],:]) 
146 µs ± 194 ns per loop (mean ± std. dev. of 7 runs, 10000 loops e 
相關問題