一个非常快速和简单的错误,我无法弄清楚来挽救我的生命:
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)
预期输出是我的临时数组的每个 ROW 的非零数字:
[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 在引擎盖下的工作方式有关。任何提示将不胜感激!
最佳答案
如文档中所述 -
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])]
关于python - Numpy:沿轴应用返回错误:使用序列设置数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41368463/