Skip to content

BUG: Fix wrong reading sparse matrix #31991

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 7 commits into from
Apr 16, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,10 @@ def from_spmatrix(cls, data):
if ncol != 1:
raise ValueError(f"'data' must have a single column, not '{ncol}'")

# when sparse data has explicit zeros, eliminate them.
if data.nnz != data.count_nonzero():
data.eliminate_zeros()

# our sparse index classes require that the positions be strictly
# increasing. So we need to sort loc, and arr accordingly.
arr = data.data
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/arrays/sparse/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,19 @@ def test_from_spmatrix(self, size, format):
expected = mat.toarray().ravel()
tm.assert_numpy_array_equal(result, expected)

@pytest.mark.parametrize("format", ["coo", "csc", "csr"])
@td.skip_if_no_scipy
def test_from_spmatrix_including_explicit_zero(self, format):
import scipy.sparse

mat = scipy.sparse.random(10, 1, density=0.5, format=format)
mat.data[0] = 0
result = SparseArray.from_spmatrix(mat)

result = np.asarray(result)
expected = mat.toarray().ravel()
tm.assert_numpy_array_equal(result, expected)

@td.skip_if_no_scipy
def test_from_spmatrix_raises(self):
import scipy.sparse
Expand Down