Skip to content

Commit

Permalink
Merge pull request numpy#28008 from WarrenWeckesser/fix-matrix-unique
Browse files Browse the repository at this point in the history
BUG: Fix handling of matrix class in np.unique.
  • Loading branch information
charris authored Dec 16, 2024
2 parents 6e4b4ec + 4821b8f commit d9c8ed5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
4 changes: 4 additions & 0 deletions numpy/lib/_arraysetops_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ def _unique1d(ar, return_index=False, return_inverse=False,
Find the unique elements of an array, ignoring shape.
"""
ar = np.asanyarray(ar).flatten()
if len(ar.shape) != 1:
# np.matrix, and maybe some other array subclasses, insist on keeping
# two dimensions for all operations. Coerce to an ndarray in such cases.
ar = np.asarray(ar).flatten()

optional_indices = return_index or return_inverse

Expand Down
17 changes: 17 additions & 0 deletions numpy/lib/tests/test_arraysetops.py
Original file line number Diff line number Diff line change
Expand Up @@ -998,3 +998,20 @@ def test_unique_inverse_shape(self):
assert_array_equal(expected_values, result.values)
assert_array_equal(expected_inverse, result.inverse_indices)
assert_array_equal(arr, result.values[result.inverse_indices])

@pytest.mark.parametrize(
'data',
[[[1, 1, 1],
[1, 1, 1]],
[1, 3, 2],
1],
)
@pytest.mark.parametrize('transpose', [False, True])
@pytest.mark.parametrize('dtype', [np.int32, np.float64])
def test_unique_with_matrix(self, data, transpose, dtype):
mat = np.matrix(data).astype(dtype)
if transpose:
mat = mat.T
u = np.unique(mat)
expected = np.unique(np.asarray(mat))
assert_array_equal(u, expected, strict=True)

0 comments on commit d9c8ed5

Please sign in to comment.