Skip to content

Commit 2974232

Browse files
committed
fixup! BUG: Made SparseDataFrame.fillna() fill all NaNs
1 parent 4bc01a1 commit 2974232

File tree

3 files changed

+9
-11
lines changed

3 files changed

+9
-11
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ Groupby/Resample/Rolling
178178
Sparse
179179
^^^^^^
180180

181+
- Bug in :func:`SparseDataFrame.fillna` not filling all NaNs when frame was instantiated from SciPy sparse matrix (:issue:`16112`)
181182

182183

183184
Reshaping

pandas/core/sparse/array.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -595,9 +595,8 @@ def fillna(self, value, downcast=None):
595595
if issubclass(self.dtype.type, np.floating):
596596
value = float(value)
597597

598-
new_values = self.sp_values.copy()
599-
new_values[isnull(new_values)] = value
600-
fill_value = value if isnull(self.fill_value) else self.fill_value
598+
new_values = np.where(isnull(self.sp_values), value, self.sp_values)
599+
fill_value = value if self._null_fill_value else self.fill_value
601600

602601
return self._simple_new(new_values, self.sp_index,
603602
fill_value=fill_value)

pandas/tests/sparse/test_frame.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -1252,7 +1252,6 @@ def test_from_scipy_correct_ordering(spmatrix):
12521252
tm.skip_if_no_package('scipy')
12531253

12541254
arr = np.arange(1, 5).reshape(2, 2)
1255-
12561255
try:
12571256
spm = spmatrix(arr)
12581257
assert spm.dtype == arr.dtype
@@ -1268,9 +1267,9 @@ def test_from_scipy_correct_ordering(spmatrix):
12681267
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())
12691268

12701269

1271-
def test_from_scipy_object_fillna(spmatrix):
1270+
def test_from_scipy_fillna(spmatrix):
12721271
# GH 16112
1273-
tm.skip_if_no_package('scipy', max_version='0.19.0')
1272+
tm.skip_if_no_package('scipy')
12741273

12751274
arr = np.eye(3)
12761275
arr[1:, 0] = np.nan
@@ -1287,12 +1286,11 @@ def test_from_scipy_object_fillna(spmatrix):
12871286
sdf = pd.SparseDataFrame(spm).fillna(-1.0)
12881287

12891288
# Returning frame should fill all nan values with -1.0
1290-
expected = pd.SparseDataFrame({0: {0: 1.0, 1: np.nan, 2: np.nan},
1291-
1: {0: np.nan, 1: 1.0, 2: np.nan},
1292-
2: {0: np.nan, 1: np.nan, 2: 1.0}}
1293-
).fillna(-1.0)
1289+
expected = pd.SparseDataFrame([[1, -1, -1],
1290+
[-1, 1, -1],
1291+
[-1, -1, 1.]])
12941292

1295-
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())
1293+
tm.assert_numpy_array_equal(sdf.values, expected.values)
12961294

12971295

12981296
class TestSparseDataFrameArithmetic(object):

0 commit comments

Comments
 (0)