Skip to content

Commit 5348e06

Browse files
npradjreback
authored andcommitted
BUG: Fix inconsistency between the shape properties of SparseSeries and SparseArray (#21126) (#21198)
1 parent 7647969 commit 5348e06

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

doc/source/whatsnew/v0.23.1.txt

+5
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ Categorical
6767
- Bug in :func:`pandas.util.testing.assert_index_equal` which raised ``AssertionError`` incorrectly, when comparing two :class:`CategoricalIndex` objects with param ``check_categorical=False`` (:issue:`19776`)
6868
- Bug in :meth:`Categorical.fillna` incorrectly raising a ``TypeError`` when `value` the individual categories are iterable and `value` is an iterable (:issue:`21097`, :issue:`19788`)
6969

70+
Sparse
71+
^^^^^^
72+
73+
- Bug in :attr:`SparseArray.shape` which previously only returned the shape :attr:`SparseArray.sp_values` (:issue:`21126`)
74+
7075
Conversion
7176
^^^^^^^^^^
7277

pandas/core/sparse/array.py

+5
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,7 @@ def __reduce__(self):
290290
"""Necessary for making this object picklable"""
291291
object_state = list(np.ndarray.__reduce__(self))
292292
subclass_state = self.fill_value, self.sp_index
293+
object_state[2] = self.sp_values.__reduce__()[2]
293294
object_state[2] = (object_state[2], subclass_state)
294295
return tuple(object_state)
295296

@@ -339,6 +340,10 @@ def values(self):
339340
output.put(int_index.indices, self)
340341
return output
341342

343+
@property
344+
def shape(self):
345+
return (len(self),)
346+
342347
@property
343348
def sp_values(self):
344349
# caching not an option, leaks memory

pandas/tests/sparse/test_array.py

+11
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,17 @@ def test_values_asarray(self):
454454
assert_almost_equal(self.arr.to_dense(), self.arr_data)
455455
assert_almost_equal(self.arr.sp_values, np.asarray(self.arr))
456456

457+
@pytest.mark.parametrize('data,shape,dtype', [
458+
([0, 0, 0, 0, 0], (5,), None),
459+
([], (0,), None),
460+
([0], (1,), None),
461+
(['A', 'A', np.nan, 'B'], (4,), np.object)
462+
])
463+
def test_shape(self, data, shape, dtype):
464+
# GH 21126
465+
out = SparseArray(data, dtype=dtype)
466+
assert out.shape == shape
467+
457468
def test_to_dense(self):
458469
vals = np.array([1, np.nan, np.nan, 3, np.nan])
459470
res = SparseArray(vals).to_dense()

0 commit comments

Comments
 (0)