Skip to content

Commit 74eb9ac

Browse files
committed
BUG: SparseSeries.to_frame results in dense
1 parent f7ba46d commit 74eb9ac

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

doc/source/whatsnew/v0.18.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ These changes conform sparse handling to return the correct types and work to ma
8989
- Bug in ``SparseSeries.__repr__`` raises ``TypeError`` when it is longer than ``max_rows`` (:issue:`10560`)
9090
- Bug in ``SparseSeries.shape`` ignores ``fill_value`` (:issue:`10452`)
9191
- Bug in ``SparseSeries.reindex`` incorrectly handle ``fill_value`` (:issue:`12797`)
92+
- Bug in ``SparseArray.to_frame()`` results in ``DataFrame``, rather than ``SparseDataFrame`` (:issue:`9850`)
9293
- Bug in ``SparseArray.to_dense()`` does not preserve ``dtype`` (:issue:`10648`)
9394
- Bug in ``SparseArray.to_dense()`` incorrectly handle ``fill_value`` (:issue:`12797`)
9495

pandas/sparse/series.py

+5
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,11 @@ def from_array(cls, arr, index=None, name=None, copy=False,
262262
def _constructor(self):
263263
return SparseSeries
264264

265+
@property
266+
def _constructor_expanddim(self):
267+
from pandas.sparse.api import SparseDataFrame
268+
return SparseDataFrame
269+
265270
@property
266271
def kind(self):
267272
if isinstance(self.sp_index, BlockIndex):

pandas/sparse/tests/test_series.py

+17
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,23 @@ def test_kind(self):
333333
self.assertEqual(self.bseries.kind, 'block')
334334
self.assertEqual(self.iseries.kind, 'integer')
335335

336+
def test_to_frame(self):
337+
# GH 9850
338+
s = pd.SparseSeries([1, 2, 0, nan, 4, nan, 0], name='x')
339+
exp = pd.SparseDataFrame({'x': [1, 2, 0, nan, 4, nan, 0]})
340+
tm.assert_sp_frame_equal(s.to_frame(), exp)
341+
342+
exp = pd.SparseDataFrame({'y': [1, 2, 0, nan, 4, nan, 0]})
343+
tm.assert_sp_frame_equal(s.to_frame(name='y'), exp)
344+
345+
s = pd.SparseSeries([1, 2, 0, nan, 4, nan, 0], name='x', fill_value=0)
346+
exp = pd.SparseDataFrame({'x': [1, 2, 0, nan, 4, nan, 0]},
347+
default_fill_value=0)
348+
349+
tm.assert_sp_frame_equal(s.to_frame(), exp)
350+
exp = pd.DataFrame({'y': [1, 2, 0, nan, 4, nan, 0]})
351+
tm.assert_frame_equal(s.to_frame(name='y').to_dense(), exp)
352+
336353
def test_pickle(self):
337354
def _test_roundtrip(series):
338355
unpickled = self.round_trip_pickle(series)

0 commit comments

Comments
 (0)