Skip to content

Commit 12c58e1

Browse files
authored
BUG: .sparse.to_coo() with numeric col index without a 0 (#38567)
1 parent d71ec09 commit 12c58e1

File tree

3 files changed

+7
-3
lines changed

3 files changed

+7
-3
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ Reshaping
273273
Sparse
274274
^^^^^^
275275

276+
- Bug in :meth:`DataFrame.sparse.to_coo` raising ``KeyError`` with columns that are a numeric :class:`Index` without a 0 (:issue:`18414`)
276277
-
277278
-
278279

pandas/core/arrays/sparse/accessor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ def to_coo(self):
329329
import_optional_dependency("scipy")
330330
from scipy.sparse import coo_matrix
331331

332-
dtype = find_common_type(self._parent.dtypes)
332+
dtype = find_common_type(self._parent.dtypes.to_list())
333333
if isinstance(dtype, SparseDtype):
334334
dtype = dtype.subtype
335335

pandas/tests/arrays/sparse/test_accessor.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,14 @@ def test_from_spmatrix_columns(self, columns):
6868
expected = pd.DataFrame(mat.toarray(), columns=columns).astype(dtype)
6969
tm.assert_frame_equal(result, expected)
7070

71+
@pytest.mark.parametrize("colnames", [("A", "B"), (1, 2), (1, pd.NA), (0.1, 0.2)])
7172
@td.skip_if_no_scipy
72-
def test_to_coo(self):
73+
def test_to_coo(self, colnames):
7374
import scipy.sparse
7475

75-
df = pd.DataFrame({"A": [0, 1, 0], "B": [1, 0, 0]}, dtype="Sparse[int64, 0]")
76+
df = pd.DataFrame(
77+
{colnames[0]: [0, 1, 0], colnames[1]: [1, 0, 0]}, dtype="Sparse[int64, 0]"
78+
)
7679
result = df.sparse.to_coo()
7780
expected = scipy.sparse.coo_matrix(np.asarray(df))
7881
assert (result != expected).nnz == 0

0 commit comments

Comments
 (0)