Skip to content

BUG: SparseDataFrame may not preserve passed dtype #13866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,7 @@ Bug Fixes
- Bug in ``SparseSeries`` with ``MultiIndex`` ``[]`` indexing result may have normal ``Index`` (:issue:`13144`)
- Bug in ``SparseDataFrame`` in which ``axis=None`` did not default to ``axis=0`` (:issue:`13048`)
- Bug in ``SparseSeries`` and ``SparseDataFrame`` creation with ``object`` dtype may raise ``TypeError`` (:issue:`11633`)
- Bug in ``SparseDataFrame`` doesn't respect passed ``SparseArray`` or ``SparseSeries`` 's dtype and ``fill_value`` (:issue:`13866`)
- Bug when passing a not-default-indexed ``Series`` as ``xerr`` or ``yerr`` in ``.plot()`` (:issue:`11858`)
- Bug in matplotlib ``AutoDataFormatter``; this restores the second scaled formatting and re-adds micro-second scaled formatting (:issue:`13131`)
- Bug in selection from a ``HDFStore`` with a fixed format and ``start`` and/or ``stop`` specified will now return the selected range (:issue:`8287`)
Expand Down
7 changes: 2 additions & 5 deletions pandas/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import pandas as pd
from pandas.core.base import PandasObject
import pandas.core.common as com

from pandas import compat, lib
from pandas.compat import range
Expand Down Expand Up @@ -577,11 +576,9 @@ def _maybe_to_dense(obj):


def _maybe_to_sparse(array):
""" array must be SparseSeries or SparseArray """
if isinstance(array, ABCSparseSeries):
array = SparseArray(array.values, sparse_index=array.sp_index,
fill_value=array.fill_value, copy=True)
if not isinstance(array, SparseArray):
array = com._values_from_object(array)
array = array.values.copy()
return array


Expand Down
2 changes: 1 addition & 1 deletion pandas/sparse/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def _init_dict(self, data, index, columns, dtype=None):
if not isinstance(v, SparseSeries):
v = sp_maker(v.values)
elif isinstance(v, SparseArray):
v = sp_maker(v.values)
v = v.copy()
else:
if isinstance(v, dict):
v = [v.get(i, nan) for i in index]
Expand Down
22 changes: 22 additions & 0 deletions pandas/sparse/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,28 @@ def test_constructor_from_series(self):
# without sparse value raises error
# df2 = SparseDataFrame([x2_sparse, y])

def test_constructor_preserve_attr(self):
# GH 13866
arr = pd.SparseArray([1, 0, 3, 0], dtype=np.int64, fill_value=0)
self.assertEqual(arr.dtype, np.int64)
self.assertEqual(arr.fill_value, 0)

df = pd.SparseDataFrame({'x': arr})
self.assertEqual(df['x'].dtype, np.int64)
self.assertEqual(df['x'].fill_value, 0)

s = pd.SparseSeries(arr, name='x')
self.assertEqual(s.dtype, np.int64)
self.assertEqual(s.fill_value, 0)

df = pd.SparseDataFrame(s)
self.assertEqual(df['x'].dtype, np.int64)
self.assertEqual(df['x'].fill_value, 0)

df = pd.SparseDataFrame({'x': s})
self.assertEqual(df['x'].dtype, np.int64)
self.assertEqual(df['x'].fill_value, 0)

def test_dtypes(self):
df = DataFrame(np.random.randn(10000, 4))
df.ix[:9998] = np.nan
Expand Down
9 changes: 9 additions & 0 deletions pandas/sparse/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,15 @@ def test_construct_DataFrame_with_sp_series(self):
result = df.ftypes
tm.assert_series_equal(expected, result)

def test_constructor_preserve_attr(self):
arr = pd.SparseArray([1, 0, 3, 0], dtype=np.int64, fill_value=0)
self.assertEqual(arr.dtype, np.int64)
self.assertEqual(arr.fill_value, 0)

s = pd.SparseSeries(arr, name='x')
self.assertEqual(s.dtype, np.int64)
self.assertEqual(s.fill_value, 0)

def test_series_density(self):
# GH2803
ts = Series(np.random.randn(10))
Expand Down
19 changes: 18 additions & 1 deletion pandas/tests/series/test_subclass.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# coding=utf-8
# pylint: disable-msg=E1101,W0612

import numpy as np
import pandas as pd
import pandas.util.testing as tm


Expand Down Expand Up @@ -32,6 +34,11 @@ def test_to_frame(self):
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)


class TestSparseSeriesSubclassing(tm.TestCase):

_multiprocess_can_split_ = True

def test_subclass_sparse_slice(self):
s = tm.SubclassedSparseSeries([1, 2, 3, 4, 5])
tm.assert_sp_series_equal(s.loc[1:3],
Expand All @@ -53,5 +60,15 @@ def test_subclass_sparse_addition(self):
def test_subclass_sparse_to_frame(self):
s = tm.SubclassedSparseSeries([1, 2], index=list('abcd'), name='xxx')
res = s.to_frame()
exp = tm.SubclassedSparseDataFrame({'xxx': [1, 2]}, index=list('abcd'))

exp_arr = pd.SparseArray([1, 2], dtype=np.int64, kind='block')
exp = tm.SubclassedSparseDataFrame({'xxx': exp_arr},
index=list('abcd'))
tm.assert_sp_frame_equal(res, exp)

s = tm.SubclassedSparseSeries([1.1, 2.1], index=list('abcd'),
name='xxx')
res = s.to_frame()
exp = tm.SubclassedSparseDataFrame({'xxx': [1.1, 2.1]},
index=list('abcd'))
tm.assert_sp_frame_equal(res, exp)