Skip to content

Commit bb07da9

Browse files
kristopheryahookeitakurita
authored andcommitted
BUG: Made SparseDataFrame.fillna() fill all NaNs
1 parent 9da7798 commit bb07da9

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

pandas/core/sparse/array.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -595,12 +595,13 @@ 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+
598601
if self._null_fill_value:
599-
return self._simple_new(self.sp_values, self.sp_index,
602+
return self._simple_new(new_values, self.sp_index,
600603
fill_value=value)
601604
else:
602-
new_values = self.sp_values.copy()
603-
new_values[isnull(new_values)] = value
604605
return self._simple_new(new_values, self.sp_index,
605606
fill_value=self.fill_value)
606607

pandas/tests/sparse/test_frame.py

+27
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,32 @@ 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}}).fillna(-1.0)
1293+
1294+
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())
1295+
1296+
12701297
class TestSparseDataFrameArithmetic(object):
12711298

12721299
def test_numeric_op_scalar(self):

0 commit comments

Comments
 (0)