From 74eb9ac0118cec4a0269e52384002043eb898893 Mon Sep 17 00:00:00 2001 From: sinhrks Date: Sat, 9 Apr 2016 13:05:25 +0900 Subject: [PATCH] BUG: SparseSeries.to_frame results in dense --- doc/source/whatsnew/v0.18.1.txt | 1 + pandas/sparse/series.py | 5 +++++ pandas/sparse/tests/test_series.py | 17 +++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/doc/source/whatsnew/v0.18.1.txt b/doc/source/whatsnew/v0.18.1.txt index 1a0d656eea8c1..7d79367cef1e2 100644 --- a/doc/source/whatsnew/v0.18.1.txt +++ b/doc/source/whatsnew/v0.18.1.txt @@ -89,6 +89,7 @@ These changes conform sparse handling to return the correct types and work to ma - Bug in ``SparseSeries.__repr__`` raises ``TypeError`` when it is longer than ``max_rows`` (:issue:`10560`) - Bug in ``SparseSeries.shape`` ignores ``fill_value`` (:issue:`10452`) - Bug in ``SparseSeries.reindex`` incorrectly handle ``fill_value`` (:issue:`12797`) +- Bug in ``SparseArray.to_frame()`` results in ``DataFrame``, rather than ``SparseDataFrame`` (:issue:`9850`) - Bug in ``SparseArray.to_dense()`` does not preserve ``dtype`` (:issue:`10648`) - Bug in ``SparseArray.to_dense()`` incorrectly handle ``fill_value`` (:issue:`12797`) diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py index fdacf1cffb485..c6e4f9297007d 100644 --- a/pandas/sparse/series.py +++ b/pandas/sparse/series.py @@ -262,6 +262,11 @@ def from_array(cls, arr, index=None, name=None, copy=False, def _constructor(self): return SparseSeries + @property + def _constructor_expanddim(self): + from pandas.sparse.api import SparseDataFrame + return SparseDataFrame + @property def kind(self): if isinstance(self.sp_index, BlockIndex): diff --git a/pandas/sparse/tests/test_series.py b/pandas/sparse/tests/test_series.py index 3d297ba55297c..fe05108cb993c 100644 --- a/pandas/sparse/tests/test_series.py +++ b/pandas/sparse/tests/test_series.py @@ -333,6 +333,23 @@ def test_kind(self): self.assertEqual(self.bseries.kind, 'block') self.assertEqual(self.iseries.kind, 'integer') + def test_to_frame(self): + # GH 9850 + s = pd.SparseSeries([1, 2, 0, nan, 4, nan, 0], name='x') + exp = pd.SparseDataFrame({'x': [1, 2, 0, nan, 4, nan, 0]}) + tm.assert_sp_frame_equal(s.to_frame(), exp) + + exp = pd.SparseDataFrame({'y': [1, 2, 0, nan, 4, nan, 0]}) + tm.assert_sp_frame_equal(s.to_frame(name='y'), exp) + + s = pd.SparseSeries([1, 2, 0, nan, 4, nan, 0], name='x', fill_value=0) + exp = pd.SparseDataFrame({'x': [1, 2, 0, nan, 4, nan, 0]}, + default_fill_value=0) + + tm.assert_sp_frame_equal(s.to_frame(), exp) + exp = pd.DataFrame({'y': [1, 2, 0, nan, 4, nan, 0]}) + tm.assert_frame_equal(s.to_frame(name='y').to_dense(), exp) + def test_pickle(self): def _test_roundtrip(series): unpickled = self.round_trip_pickle(series)