Skip to content

Commit 6354580

Browse files
fhoang7jreback
authored andcommitted
Add more specific error message when user passes incorrect matrix format to from_coo (#26584)
1 parent 0e3bf7f commit 6354580

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ Sparse
694694
- Significant speedup in :class:`SparseArray` initialization that benefits most operations, fixing performance regression introduced in v0.20.0 (:issue:`24985`)
695695
- Bug in :class:`SparseFrame` constructor where passing ``None`` as the data would cause ``default_fill_value`` to be ignored (:issue:`16807`)
696696
- Bug in :class:`SparseDataFrame` when adding a column in which the length of values does not match length of index, ``AssertionError`` is raised instead of raising ``ValueError`` (:issue:`25484`)
697-
697+
- Introduce a better error message in :meth:`Series.sparse.from_coo` so it returns a ``TypeError`` for inputs that are not coo matrices (:issue:`26554`)
698698

699699
Other
700700
^^^^^

pandas/core/sparse/scipy_sparse.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,19 @@ def _coo_to_sparse_series(A, dense_index: bool = False,
130130
Returns
131131
-------
132132
Series or SparseSeries
133+
134+
Raises
135+
------
136+
TypeError if A is not a coo_matrix
137+
133138
"""
134139
from pandas import SparseDtype
135140

136-
s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
141+
try:
142+
s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
143+
except AttributeError:
144+
raise TypeError('Expected coo_matrix. Got {} instead.'
145+
.format(type(A).__name__))
137146
s = s.sort_index()
138147
if sparse_series:
139148
# TODO(SparseSeries): remove this and the sparse_series keyword.

pandas/tests/arrays/sparse/test_accessor.py

+10
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,13 @@ def test_series_from_coo(self, dtype, dense_index):
119119
)
120120

121121
tm.assert_series_equal(result, expected)
122+
123+
@td.skip_if_no_scipy
124+
def test_series_from_coo_incorrect_format_raises(self):
125+
# gh-26554
126+
import scipy.sparse
127+
m = scipy.sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
128+
with pytest.raises(TypeError,
129+
match='Expected coo_matrix. Got csr_matrix instead.'
130+
):
131+
pd.Series.sparse.from_coo(m)

0 commit comments

Comments
 (0)