python - Numpy:沿轴应用返回错误:使用序列设置数组元素

标签 python 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)

预期输出是我的临时数组的每个 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/

相关文章:

python - 根据列表中的字符串重命名 pandas 中的列

python - 使用列表列表进行 Numpy 索引

Python 脚本进入不正确的 if 语句

python - Python Django 中的 ORM 数据建模

python - NumPy 点积 : take product of vector products (rather than sum)

python - 无法以非 root 用户身份导入 pip 安装的包

python - Matlab 和 Numpy 之间冲突的特征向量输出

Python:im2col 的实现利用了 6 维数组的优势?

python - pandas df.apply TypeError 数据类型不理解

python - 序列化 `numpy.dtype` 对象 : human readable