Skip to content

Commit 7f54bec

Browse files
BUG: Fix SparseFrameAccessor.to_dense return type (#59967)
* BUG: Fix SparseFrameAccessor.to_dense return type * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 58de332 commit 7f54bec

File tree

3 files changed

+8
-3
lines changed

3 files changed

+8
-3
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,7 @@ Sparse
682682
^^^^^^
683683
- Bug in :class:`SparseDtype` for equal comparison with na fill value. (:issue:`54770`)
684684
- Bug in :meth:`DataFrame.sparse.from_spmatrix` which hard coded an invalid ``fill_value`` for certain subtypes. (:issue:`59063`)
685+
- Bug in :meth:`DataFrame.sparse.to_dense` which ignored subclassing and always returned an instance of :class:`DataFrame` (:issue:`59913`)
685686

686687
ExtensionArray
687688
^^^^^^^^^^^^^^

pandas/core/arrays/sparse/accessor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -369,10 +369,10 @@ def to_dense(self) -> DataFrame:
369369
1 1
370370
2 0
371371
"""
372-
from pandas import DataFrame
373-
374372
data = {k: v.array.to_dense() for k, v in self._parent.items()}
375-
return DataFrame(data, index=self._parent.index, columns=self._parent.columns)
373+
return self._parent._constructor(
374+
data, index=self._parent.index, columns=self._parent.columns
375+
)
376376

377377
def to_coo(self) -> spmatrix:
378378
"""

pandas/tests/arrays/sparse/test_accessor.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,3 +252,7 @@ def test_with_column_named_sparse(self):
252252
# https://github.com/pandas-dev/pandas/issues/30758
253253
df = pd.DataFrame({"sparse": pd.arrays.SparseArray([1, 2])})
254254
assert isinstance(df.sparse, pd.core.arrays.sparse.accessor.SparseFrameAccessor)
255+
256+
def test_subclassing(self):
257+
df = tm.SubclassedDataFrame({"sparse": pd.arrays.SparseArray([1, 2])})
258+
assert isinstance(df.sparse.to_dense(), tm.SubclassedDataFrame)

0 commit comments

Comments
 (0)