问题在于,
bincount并非总是返回相同形状的对象,尤其是在缺少值时。例如:
>>> m = np.array([[0,0,1],[1,1,0],[1,1,1]])>>> np.apply_along_axis(np.bincount, 1, m)array([[2, 1], [1, 2], [0, 3]])>>> [np.bincount(m[i]) for i in range(m.shape[1])][array([2, 1]), array([1, 2]), array([0, 3])]
可以,但是:
>>> m = np.array([[0,0,0],[1,1,0],[1,1,0]])>>> marray([[0, 0, 0], [1, 1, 0], [1, 1, 0]])>>> [np.bincount(m[i]) for i in range(m.shape[1])][array([3]), array([1, 2]), array([1, 2])]>>> np.apply_along_axis(np.bincount, 1, m)Traceback (most recent call last): File "<ipython-input-49-72e06e26a718>", line 1, in <module> np.apply_along_axis(np.bincount, 1, m) File "/usr/local/lib/python2.7/dist-packages/numpy/lib/shape_base.py", line 117, in apply_along_axis outarr[tuple(i.tolist())] = resValueError: could not broadcast input array from shape (2) into shape (1)
惯于。
您可以使用
minlength参数,并使用
lambda或
partial或其他方式传递该参数:
>>> np.apply_along_axis(lambda x: np.bincount(x, minlength=2), axis=1, arr=m)array([[3, 0], [1, 2], [1, 2]])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)