Skip to content
Merged
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ Reshaping

Sparse
^^^^^^

- Bug in :class:`SparseDataFrame` arithmetic operations incorrectly casting inputs to float (:issue:`28107`)
-
-

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/sparse/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,8 +576,8 @@ def _combine_match_index(self, other, func, level=None):
this, other = self.align(other, join="outer", axis=0, level=level, copy=False)

new_data = {}
for col, series in this.items():
new_data[col] = func(series.values, other.values)
for col in this.columns:
new_data[col] = func(this[col], other)

fill_value = self._get_op_result_fill_value(other, func)

Expand All @@ -603,7 +603,7 @@ def _combine_match_columns(self, other, func, level=None):
new_data = {}

for col in left.columns:
new_data[col] = func(left[col], float(right[col]))
new_data[col] = func(left[col], right[col])

return self._constructor(
new_data,
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/sparse/frame/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,22 @@ def test_comparison_op_scalar(self):
assert isinstance(res, pd.SparseDataFrame)
tm.assert_frame_equal(res.to_dense(), df != 0)

def test_add_series_retains_dtype(self):
# SparseDataFrame._combine_match_columns used to incorrectly cast
# to float
d = {0: [2j, 3j], 1: [0, 1]}
sdf = SparseDataFrame(data=d, default_fill_value=1)
result = sdf + sdf[0]

df = sdf.to_dense()
expected = df + df[0]
tm.assert_frame_equal(result.to_dense(), expected)

# Make it explicit to be on the safe side
edata = {0: [4j, 5j], 1: [3j, 1 + 3j]}
expected = DataFrame(edata)
tm.assert_frame_equal(result.to_dense(), expected)


@pytest.mark.filterwarnings("ignore:Sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")
Expand Down