Skip to content

BUG: provide SparseArray creation in a platform independent manner #12936

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
Apr 20, 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
36 changes: 29 additions & 7 deletions pandas/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def __new__(cls, data, sparse_index=None, index=None, kind='integer',
values, sparse_index = make_sparse(data, kind=kind,
fill_value=fill_value)
else:
values = data
values = _sanitize_values(data)
if len(values) != sparse_index.npoints:
raise AssertionError("Non array-like type {0} must have"
" the same length as the"
Expand Down Expand Up @@ -515,6 +515,33 @@ def _maybe_to_sparse(array):
return array


def _sanitize_values(arr):
"""
return an ndarray for our input,
in a platform independent manner
"""

if hasattr(arr, 'values'):
arr = arr.values
else:

# scalar
if lib.isscalar(arr):
arr = [arr]

# ndarray
if isinstance(arr, np.ndarray):
pass

elif com.is_list_like(arr) and len(arr) > 0:
arr = com._possibly_convert_platform(arr)

else:
arr = np.asarray(arr)

return arr


def make_sparse(arr, kind='block', fill_value=nan):
"""
Convert ndarray to sparse format
Expand All @@ -529,13 +556,8 @@ def make_sparse(arr, kind='block', fill_value=nan):
-------
(sparse_values, index) : (ndarray, SparseIndex)
"""
if hasattr(arr, 'values'):
arr = arr.values
else:
if lib.isscalar(arr):
arr = [arr]
arr = np.asarray(arr)

arr = _sanitize_values(arr)
length = len(arr)

if np.isnan(fill_value):
Expand Down
9 changes: 9 additions & 0 deletions pandas/sparse/tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ def test_constructor_spindex_dtype(self):
self.assertEqual(arr.dtype, np.int64)
self.assertTrue(np.isnan(arr.fill_value))

# scalar input
arr = SparseArray(data=1,
sparse_index=IntIndex(1, [0]),
dtype=None)
exp = SparseArray([1], dtype=None)
tm.assert_sp_array_equal(arr, exp)
self.assertEqual(arr.dtype, np.int64)
self.assertTrue(np.isnan(arr.fill_value))

arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2]),
fill_value=0, dtype=None)
exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=None)
Expand Down