我看到了numpy bincount的行为,我无法理解。我想以行方式将2D数组中的值装箱,并看到下面的行为。为什么它可以与dbArray一起工作,但与simarray一起失败?
>>> dbArray
array([[1, 0, 1, 0, 1],
[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 1, 0, 1, 0]])
>>> N.apply_along_axis(N.bincount,1,dbArray)
array([[2, 3],
[0, 5],
[1, 4],
[4, 1],
[3, 2],
[3, 2]], dtype=int64)
>>> simarray
array([[2, 0, 2, 0, 2],
[2, 1, 2, 1, 2],
[2, 1, 1, 1, 2],
[2, 0, 1, 0, 1],
[1, 0, 1, 1, 2],
[1, 1, 1, 1, 1]])
>>> N.apply_along_axis(N.bincount,1,simarray)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
N.apply_along_axis(N.bincount,1,simarray)
File "C:\Python27\lib\site-packages\numpy\lib\shape_base.py", line 118, in apply_along_axis
outarr[tuple(i.tolist())] = res
ValueError: could not broadcast input array from shape (2) into shape (3)
3条答案
按热度按时间smdnsysy1#
问题是
bincount
并不总是返回相同形状的对象,特别是当值丢失时。例如:工作,但:
不会。
您可以使用
minlength
参数,并使用lambda
或partial
或其他方式传递它:lnlaulya2#
正如@DSM已经提到的,在不知道数组的最大值的情况下,无法对2d数组进行bincount,因为这意味着数组大小的不一致。
但是由于numpy强大的索引功能,很容易实现更快的2d bincount,因为它不使用连接或任何东西。
doinxwow3#
这是一个完全按照你的要求执行的函数,但没有任何循环。