Skip to content

Commit 05cc959

Browse files
jbrockmendeljreback
authored andcommitted
BUG: SparseDataFrame op incorrectly casting to float (#28107)
1 parent 42d6ee7 commit 05cc959

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ Reshaping
189189

190190
Sparse
191191
^^^^^^
192-
192+
- Bug in :class:`SparseDataFrame` arithmetic operations incorrectly casting inputs to float (:issue:`28107`)
193193
-
194194
-
195195

pandas/core/sparse/frame.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -576,8 +576,8 @@ def _combine_match_index(self, other, func, level=None):
576576
this, other = self.align(other, join="outer", axis=0, level=level, copy=False)
577577

578578
new_data = {}
579-
for col, series in this.items():
580-
new_data[col] = func(series.values, other.values)
579+
for col in this.columns:
580+
new_data[col] = func(this[col], other)
581581

582582
fill_value = self._get_op_result_fill_value(other, func)
583583

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

605605
for col in left.columns:
606-
new_data[col] = func(left[col], float(right[col]))
606+
new_data[col] = func(left[col], right[col])
607607

608608
return self._constructor(
609609
new_data,

pandas/tests/sparse/frame/test_frame.py

+16
Original file line numberDiff line numberDiff line change
@@ -1487,6 +1487,22 @@ def test_comparison_op_scalar(self):
14871487
assert isinstance(res, pd.SparseDataFrame)
14881488
tm.assert_frame_equal(res.to_dense(), df != 0)
14891489

1490+
def test_add_series_retains_dtype(self):
1491+
# SparseDataFrame._combine_match_columns used to incorrectly cast
1492+
# to float
1493+
d = {0: [2j, 3j], 1: [0, 1]}
1494+
sdf = SparseDataFrame(data=d, default_fill_value=1)
1495+
result = sdf + sdf[0]
1496+
1497+
df = sdf.to_dense()
1498+
expected = df + df[0]
1499+
tm.assert_frame_equal(result.to_dense(), expected)
1500+
1501+
# Make it explicit to be on the safe side
1502+
edata = {0: [4j, 5j], 1: [3j, 1 + 3j]}
1503+
expected = DataFrame(edata)
1504+
tm.assert_frame_equal(result.to_dense(), expected)
1505+
14901506

14911507
@pytest.mark.filterwarnings("ignore:Sparse:FutureWarning")
14921508
@pytest.mark.filterwarnings("ignore:DataFrame.to_sparse:FutureWarning")

0 commit comments

Comments
 (0)