Skip to content

Commit

Permalink
Add COO.nonzero method. (#148)
Browse files Browse the repository at this point in the history
  • Loading branch information
hameerabbasi authored and mrocklin committed May 3, 2018
1 parent 8f2a9ae commit 3a53e87
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/generated/sparse.COO.nonzero.rst
@@ -0,0 +1,6 @@
COO.nonzero
===========

.. currentmodule:: sparse

.. automethod:: COO.nonzero
1 change: 1 addition & 0 deletions docs/generated/sparse.COO.rst
Expand Up @@ -61,6 +61,7 @@ COO
COO.dot
COO.reshape
COO.transpose
COO.nonzero

.. rubric:: Utility functions
.. autosummary::
Expand Down
21 changes: 21 additions & 0 deletions sparse/coo/core.py
Expand Up @@ -1437,6 +1437,27 @@ def maybe_densify(self, max_size=1000, min_density=0.25):
raise ValueError("Operation would require converting "
"large sparse array to dense")

def nonzero(self):
"""
Get the indices where this array is nonzero.
Returns
-------
idx : tuple[numpy.ndarray]
The indices where this array is nonzero.
See Also
--------
:obj:`numpy.ndarray.nonzero` : NumPy equivalent function
Examples
--------
>>> s = COO.from_numpy(np.eye(5))
>>> s.nonzero()
(array([0, 1, 2, 3, 4], dtype=uint8), array([0, 1, 2, 3, 4], dtype=uint8))
"""
return tuple(self.coords)


def _keepdims(original, new, axis):
shape = list(original.shape)
Expand Down
21 changes: 21 additions & 0 deletions sparse/tests/test_coo.py
Expand Up @@ -1374,3 +1374,24 @@ def test_two_arg_where():

with pytest.raises(ValueError):
sparse.where(cs, xs)


def test_nonzero():
s = sparse.random((2, 3, 4), density=0.5)
x = s.todense()

expected = x.nonzero()
actual = s.nonzero()

assert isinstance(actual, tuple)
assert len(expected) == len(actual)

for e, a in zip(expected, actual):
assert_eq(e, a, compare_dtype=False)


def test_argwhere():
s = sparse.random((2, 3, 4), density=0.5)
x = s.todense()

assert_eq(np.argwhere(s), np.argwhere(x), compare_dtype=False)

0 comments on commit 3a53e87

Please sign in to comment.