Skip to content

Add more specific error message when user passes incorrect matrix format to from_coo #26584

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jun 2, 2019
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ Sparse
- Significant speedup in :class:`SparseArray` initialization that benefits most operations, fixing performance regression introduced in v0.20.0 (:issue:`24985`)
- Bug in :class:`SparseFrame` constructor where passing ``None`` as the data would cause ``default_fill_value`` to be ignored (:issue:`16807`)
- 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`)

- 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`)

Other
^^^^^
Expand Down
11 changes: 10 additions & 1 deletion pandas/core/sparse/scipy_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,19 @@ def _coo_to_sparse_series(A, dense_index: bool = False,
Returns
-------
Series or SparseSeries
Raises
------
TypeError if A is not a coo_matrix
"""
from pandas import SparseDtype

s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
try:
s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
except AttributeError:
raise TypeError('Expected coo_matrix. Got {} instead.'
.format(type(A).__name__))
s = s.sort_index()
if sparse_series:
# TODO(SparseSeries): remove this and the sparse_series keyword.
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/arrays/sparse/test_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,13 @@ def test_series_from_coo(self, dtype, dense_index):
)

tm.assert_series_equal(result, expected)

@td.skip_if_no_scipy
def test_series_from_coo_incorrect_format_raises_type_error(self):
# non-regression test for fix to issue #26554
import scipy.sparse
m = scipy.sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
with pytest.raises(TypeError,
match='Expected coo_matrix. Got {} instead.'.format(
type(m).__name__)):
pd.Series.sparse.from_coo(m)