Skip to content

Commit 5ec3499

Browse files
JustinZhengBCPingviinituutti
authored andcommitted
BUG GH23744 ufuncs on DataFrame keeps dtype sparseness (pandas-dev#23755)
1 parent ea5aea4 commit 5ec3499

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

doc/source/whatsnew/v0.24.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -1467,6 +1467,7 @@ Sparse
14671467
- Bug in unary inversion operator (``~``) on a ``SparseSeries`` with boolean values. The performance of this has also been improved (:issue:`22835`)
14681468
- Bug in :meth:`SparseArary.unique` not returning the unique values (:issue:`19595`)
14691469
- Bug in :meth:`SparseArray.nonzero` and :meth:`SparseDataFrame.dropna` returning shifted/incorrect results (:issue:`21172`)
1470+
- Bug in :meth:`DataFrame.apply` where dtypes would lose sparseness (:issue:`23744`)
14701471

14711472
Build Changes
14721473
^^^^^^^^^^^^^
@@ -1493,4 +1494,3 @@ Contributors
14931494
~~~~~~~~~~~~
14941495

14951496
.. contributors:: v0.23.4..HEAD
1496-

pandas/core/apply.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def get_result(self):
132132
# ufunc
133133
elif isinstance(self.f, np.ufunc):
134134
with np.errstate(all='ignore'):
135-
results = self.f(self.values)
135+
results = self.obj._data.apply('apply', func=self.f)
136136
return self.obj._constructor(data=results, index=self.index,
137137
columns=self.columns, copy=False)
138138

pandas/tests/sparse/frame/test_apply.py

+11
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,14 @@ def test_applymap(frame):
9191
# just test that it works
9292
result = frame.applymap(lambda x: x * 2)
9393
assert isinstance(result, SparseDataFrame)
94+
95+
96+
def test_apply_keep_sparse_dtype():
97+
# GH 23744
98+
sdf = SparseDataFrame(np.array([[0, 1, 0], [0, 0, 0], [0, 0, 1]]),
99+
columns=['b', 'a', 'c'], default_fill_value=1)
100+
df = DataFrame(sdf)
101+
102+
expected = sdf.apply(np.exp)
103+
result = df.apply(np.exp)
104+
tm.assert_frame_equal(expected, result)

0 commit comments

Comments
 (0)