Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: Made SparseDataFrame.fillna() fill all NaNs #16892

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
13 changes: 5 additions & 8 deletions pandas/core/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,14 +595,11 @@ def fillna(self, value, downcast=None):
if issubclass(self.dtype.type, np.floating):
value = float(value)

if self._null_fill_value:
return self._simple_new(self.sp_values, self.sp_index,
fill_value=value)
else:
new_values = self.sp_values.copy()
new_values[isnull(new_values)] = value
return self._simple_new(new_values, self.sp_index,
fill_value=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)

def sum(self, axis=0, *args, **kwargs):
"""
Expand Down
35 changes: 35 additions & 0 deletions pandas/tests/sparse/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,41 @@ def test_from_scipy_correct_ordering(spmatrix):
tm.assert_frame_equal(sdf.to_dense(), expected.to_dense())


def test_from_scipy_fillna(spmatrix):
# GH 16112
tm.skip_if_no_package('scipy')

arr = np.eye(3)
arr[1:, 0] = np.nan

try:
spm = spmatrix(arr)
assert spm.dtype == arr.dtype
except (TypeError, AssertionError):
# If conversion to sparse fails for this spmatrix type and arr.dtype,
# then the combination is not currently supported in NumPy, so we
# can just skip testing it thoroughly
return

sdf = pd.SparseDataFrame(spm).fillna(-1.0)

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

# fill_value is expected to be what .fillna() above was called with
# We don't use -1 as initial fill_value in expected SparseSeries
# construction because this way we obtain "compressed" SparseArrays,
# avoiding having to construct them ourselves
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue here is that a SDF has a fill value and doesn't propogate it to its contained series, not sure if we should. Should we check this as well? (we do, but should we)?

Copy link
Contributor Author

@kernc kernc Jul 13, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SparseSeries have fill_value, SparseDataFrames have default_fill_value for newly inserted non-SparseSeries data. We definitely should be comparing these features. Will look into .fillna() propagating fill_value.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, never mind my previous comment; .fillna() fill_value already propagates.

The docs for default_fill_value say:

Will not override SparseSeries passed in,

so propagating this is a no-go.

I can add check_series_fill_value=True param to assert_sp_frame_equal?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, this doesn't work. If series' fill_value aren't overridden, then also the underlying values (remaining e.g. [nan, 1, nan]) don't match (sdf's [-1, 1, -1]).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can construct all the SparseArrays with their sparse indices, but this feels awfully reaching into implementation details ...

Or could just use .to_dense() and compare that. That test too would fail before whereas now it doesn't.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, I am not sure of a nice solution here. Should adding Series to a Sparse DataFrame invalidate there fill_values? I think if you don't weird things happen.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But this test is the only thing that (as of yet) fails due to its strict underlying series comparison and particularly the way how the frame was constructed. Nowhere else are ill effects observed of SparseSeries having different fill_values. How about we don't break the documented API (of not overriding existing fill_values) just yet until something else surfaces?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, that's fine.

for col in expected:
expected[col].fill_value = -1

tm.assert_sp_frame_equal(sdf, expected)


class TestSparseDataFrameArithmetic(object):

def test_numeric_op_scalar(self):
Expand Down