Why is numpy.count_nonzero (arr) not working with the assigned axis value?
I have a two dimensional array and I would like to count the values ββrow by row. Even if I assign a value to the axis, axis = 1, the method still returns a single integer.
x = rng.randint(10, size=(6,3))
x
Out[120]:
array([[3, 3, 8],
[8, 8, 2],
[3, 2, 0],
[8, 8, 3],
[8, 2, 8],
[4, 3, 0]])
np.count_nonzero(x)
Out[121]: 16
np.count_nonzero(x, axis=1)
Out[122]: 16
I tried to copy the example directly from the docs page and got the same results.
np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)
Out[123]: 5
Where expected:
array([2, 3])
I am using Python 3.6
Any ideas what might cause the method to return an array of counters from different rows?
source to share
From v1.12 docs:
axis : int or tuple, optional
Axis or tuple of axes along which to count non-zeros.
Default is None, meaning that non-zeros will be counted
along a flattened version of ``a``.
.. versionadded:: 1.12.0
So this axis parameter is new.
count_nonzero
is used nonzero
( where
) to determine the size of the arrays it needs to allocate to return results. It does not need an axis parameter for this. You just need to be quick and simple. If the developers saw the use as a primary excuse, that might explain why it axis
is a late addition.
source to share