diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index e43a5f9856253..5146bd35dff30 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -219,7 +219,7 @@ Groupby/Resample/Rolling Sparse ^^^^^^ - +- Bug in ``SparseSeries`` raises ``AttributeError`` when a dictionary is passed in as data (:issue:`16777`) Reshaping diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index 9dd061e26ba06..1bc9cf5379930 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -146,10 +146,9 @@ def __init__(self, data=None, index=None, sparse_index=None, kind='block', data = data._data elif isinstance(data, (Series, dict)): - if index is None: - index = data.index.view() + data = Series(data, index=index) + index = data.index.view() - data = Series(data) res = make_sparse(data, kind=kind, fill_value=fill_value) data, sparse_index, fill_value = res diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py index b524d6bfab418..bb56f8a51897a 100644 --- a/pandas/tests/sparse/test_series.py +++ b/pandas/tests/sparse/test_series.py @@ -88,6 +88,24 @@ def setup_method(self, method): self.ziseries2 = SparseSeries(arr, index=index, kind='integer', fill_value=0) + def test_constructor_dict_input(self): + # gh-16905 + constructor_dict = {1: 1.} + index = [0, 1, 2] + + # Series with index passed in + series = pd.Series(constructor_dict) + expected = SparseSeries(series, index=index) + + result = SparseSeries(constructor_dict, index=index) + tm.assert_sp_series_equal(result, expected) + + # Series with index and dictionary with no index + expected = SparseSeries(series) + + result = SparseSeries(constructor_dict) + tm.assert_sp_series_equal(result, expected) + def test_constructor_dtype(self): arr = SparseSeries([np.nan, 1, 2, np.nan]) assert arr.dtype == np.float64