2016-12-28 65 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不会尝试堆栈子数组。

相关问题