Skip to content

Commit 4bc01a1

Browse files
kristopheryahookernc
authored andcommitted
BUG: Made SparseDataFrame.fillna() fill all NaNs
1 parent a9421af commit 4bc01a1

File tree

2 files changed

+34
-8
lines changed

2 files changed

+34
-8
lines changed

pandas/core/sparse/array.py

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

598-
if self._null_fill_value:
599-
return self._simple_new(self.sp_values, self.sp_index,
600-
fill_value=value)
601-
else:
602-
new_values = self.sp_values.copy()
603-
new_values[isnull(new_values)] = value
604-
return self._simple_new(new_values, self.sp_index,
605-
fill_value=self.fill_value)
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
601+
602+
return self._simple_new(new_values, self.sp_index,
603+
fill_value=fill_value)
606604

607605
def sum(self, axis=0, *args, **kwargs):
608606
"""

pandas/tests/sparse/test_frame.py

+28
Original file line numberDiff line numberDiff line change
@@ -1252,6 +1252,7 @@ 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+
12551256
try:
12561257
spm = spmatrix(arr)
12571258
assert spm.dtype == arr.dtype
@@ -1267,6 +1268,33 @@ def test_from_scipy_correct_ordering(spmatrix):
12671268
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())
12681269

12691270

1271+
def test_from_scipy_object_fillna(spmatrix):
1272+
# GH 16112
1273+
tm.skip_if_no_package('scipy', max_version='0.19.0')
1274+
1275+
arr = np.eye(3)
1276+
arr[1:, 0] = np.nan
1277+
1278+
try:
1279+
spm = spmatrix(arr)
1280+
assert spm.dtype == arr.dtype
1281+
except (TypeError, AssertionError):
1282+
# If conversion to sparse fails for this spmatrix type and arr.dtype,
1283+
# then the combination is not currently supported in NumPy, so we
1284+
# can just skip testing it thoroughly
1285+
return
1286+
1287+
sdf = pd.SparseDataFrame(spm).fillna(-1.0)
1288+
1289+
# 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)
1294+
1295+
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())
1296+
1297+
12701298
class TestSparseDataFrameArithmetic(object):
12711299

12721300
def test_numeric_op_scalar(self):

0 commit comments

Comments
 (0)