2016-12-28 27 views
2

一個非常快速和簡單的錯誤,我想不出來挽救我的生命:NumPy的:沿軸返回錯誤適用:設置一個數組元素與序列

temp = np.array([[5,0,3,5,6,0], 
       [2,2,1,3,0,0], 
       [5,3,4,5,3,4]]) 

def myfunc(x): 
    return x[np.nonzero(x)] 

np.apply_along_axis(myfunc, axis=1, arr=temp) 

預計產量爲非零我臨時陣列的每一行的數字:

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

不過,我發現了錯誤:ValueError異常:設置與序列中的數組元素。

如果我只是做沒有apply_along_axis,它的工作原理:

# prints [5,3,5,6] 
print temp[0][np.nonzero(temp[0])] 

奇怪的是,如果我只是添加np.mean()到MYFUNC返回第一個代碼塊的上方,它按預期工作:

# This works as expected  
temp = np.array([[5,0,3,5,6,0], 
       [2,2,1,3,0,0], 
       [5,3,4,5,3,4]]) 

def myfunc(x): 
     return np.mean(x[np.nonzero(x)]) 

np.apply_along_axis(myfunc, axis=1, arr=temp) 

我懷疑這與apply_along_axis如何在引擎蓋下工作有關。任何提示將不勝感激!

+0

通常,您應該發佈整個Traceback與您的問題。調用apply_along_axis時會發生嗎? – wwii

+0

您的'myfunc'不會返回一致形狀的結果。 – user2357112

+0

'apply_along_axis'只是迭代'其他'軸的一種便捷方式。在你的情況下,只有一維,行。所以即使它運作起來(與'np.mean'一樣),它並不是一個奇蹟般的工作者。你可以用簡單的遍歷行來完成,'[myfunc(row)for temp in row]' – hpaulj

回答

2

,如文檔中提到的 -

Returns: apply_along_axis : ndarray The output array. The shape of outarr is identical to the shape of arr, except along the axis dimension, where the length of outarr is equal to the size of the return value of func1d. If func1d returns a scalar outarr will have one fewer dimensions than arr.

因爲在不同的迭代輸出不一致的形狀,似乎我們得到的錯誤。

現在,解決你的問題,讓我整個陣列上提出的方法與np.nonzero,然後從中分離第二輸出 -

In [165]: temp = np.array([[5,0,3,5,6,0], 
    ...:     [2,2,1,3,0,0], 
    ...:     [5,3,4,5,3,4]]) 

In [166]: r,c = np.nonzero(temp) 
    ...: idx = np.unique(r,return_index=1)[1] 
    ...: out = np.split(c,idx[1:]) 
    ...: 

In [167]: out 
Out[167]: [array([0, 2, 3, 4]), array([0, 1, 2, 3]), array([0, 1, 2, 3, 4, 5])] 
+0

感謝#protip! –

1

在numpy的1.13,這個定義應該工作:

def myfunc(x): 
    res = np.empty((), dtype=object) 
    res[()] = x[np.nonzero(x)] 
    return res 

通過返回一個包含數組的0d數組,numpy不會嘗試堆棧子數組。

相關問題