Skip to content

Commit

Permalink
fixup! BUG: Made SparseDataFrame.fillna() fill all NaNs
Browse files Browse the repository at this point in the history
  • Loading branch information
kernc committed Jul 12, 2017
1 parent 4bc01a1 commit 2974232
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 11 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ Groupby/Resample/Rolling
Sparse
^^^^^^

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


Reshaping
Expand Down
5 changes: 2 additions & 3 deletions pandas/core/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,9 +595,8 @@ def fillna(self, value, downcast=None):
if issubclass(self.dtype.type, np.floating):
value = float(value)

new_values = self.sp_values.copy()
new_values[isnull(new_values)] = value
fill_value = value if isnull(self.fill_value) else self.fill_value
new_values = np.where(isnull(self.sp_values), value, self.sp_values)
fill_value = value if self._null_fill_value else self.fill_value

return self._simple_new(new_values, self.sp_index,
fill_value=fill_value)
Expand Down
14 changes: 6 additions & 8 deletions pandas/tests/sparse/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,6 @@ def test_from_scipy_correct_ordering(spmatrix):
tm.skip_if_no_package('scipy')

arr = np.arange(1, 5).reshape(2, 2)

try:
spm = spmatrix(arr)
assert spm.dtype == arr.dtype
Expand All @@ -1268,9 +1267,9 @@ def test_from_scipy_correct_ordering(spmatrix):
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())


def test_from_scipy_object_fillna(spmatrix):
def test_from_scipy_fillna(spmatrix):
# GH 16112
tm.skip_if_no_package('scipy', max_version='0.19.0')
tm.skip_if_no_package('scipy')

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

# Returning frame should fill all nan values with -1.0
expected = pd.SparseDataFrame({0: {0: 1.0, 1: np.nan, 2: np.nan},
1: {0: np.nan, 1: 1.0, 2: np.nan},
2: {0: np.nan, 1: np.nan, 2: 1.0}}
).fillna(-1.0)
expected = pd.SparseDataFrame([[1, -1, -1],
[-1, 1, -1],
[-1, -1, 1.]])

tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())
tm.assert_numpy_array_equal(sdf.values, expected.values)


class TestSparseDataFrameArithmetic(object):
Expand Down

0 comments on commit 2974232

Please sign in to comment.