Skip to content

Commit de32953

Browse files
committed
BUG: provide SparseArray creation in a platform independent manner
1 parent 5d8a935 commit de32953

File tree

2 files changed

+38
-7
lines changed

2 files changed

+38
-7
lines changed

pandas/sparse/array.py

+29-7
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def __new__(cls, data, sparse_index=None, index=None, kind='integer',
140140
values, sparse_index = make_sparse(data, kind=kind,
141141
fill_value=fill_value)
142142
else:
143-
values = data
143+
values = _sanitize_values(data)
144144
if len(values) != sparse_index.npoints:
145145
raise AssertionError("Non array-like type {0} must have"
146146
" the same length as the"
@@ -515,6 +515,33 @@ def _maybe_to_sparse(array):
515515
return array
516516

517517

518+
def _sanitize_values(arr):
519+
"""
520+
return an ndarray for our input,
521+
in a platform independent manner
522+
"""
523+
524+
if hasattr(arr, 'values'):
525+
arr = arr.values
526+
else:
527+
528+
# scalar
529+
if lib.isscalar(arr):
530+
arr = [arr]
531+
532+
# ndarray
533+
if isinstance(arr, np.ndarray):
534+
pass
535+
536+
elif com.is_list_like(arr) and len(arr) > 0:
537+
arr = com._possibly_convert_platform(arr)
538+
539+
else:
540+
arr = np.asarray(arr)
541+
542+
return arr
543+
544+
518545
def make_sparse(arr, kind='block', fill_value=nan):
519546
"""
520547
Convert ndarray to sparse format
@@ -529,13 +556,8 @@ def make_sparse(arr, kind='block', fill_value=nan):
529556
-------
530557
(sparse_values, index) : (ndarray, SparseIndex)
531558
"""
532-
if hasattr(arr, 'values'):
533-
arr = arr.values
534-
else:
535-
if lib.isscalar(arr):
536-
arr = [arr]
537-
arr = np.asarray(arr)
538559

560+
arr = _sanitize_values(arr)
539561
length = len(arr)
540562

541563
if np.isnan(fill_value):

pandas/sparse/tests/test_array.py

+9
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,15 @@ def test_constructor_spindex_dtype(self):
7676
self.assertEqual(arr.dtype, np.int64)
7777
self.assertTrue(np.isnan(arr.fill_value))
7878

79+
# scalar input
80+
arr = SparseArray(data=1,
81+
sparse_index=IntIndex(1, [0]),
82+
dtype=None)
83+
exp = SparseArray([1], dtype=None)
84+
tm.assert_sp_array_equal(arr, exp)
85+
self.assertEqual(arr.dtype, np.int64)
86+
self.assertTrue(np.isnan(arr.fill_value))
87+
7988
arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2]),
8089
fill_value=0, dtype=None)
8190
exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=None)

0 commit comments

Comments
 (0)