Skip to content

BUG GH23744 ufuncs on DataFrame keeps dtype sparseness #23755

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

Merged
merged 23 commits into from
Nov 27, 2018
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
b85bdb9
BUG-23744 DataFrame.apply keeps dtype sparseness
JustinZhengBC Nov 17, 2018
ad33f76
BUG-23744 Fix memory usage
JustinZhengBC Nov 17, 2018
c39fe11
BUG-23744 Remove unnecessary check
JustinZhengBC Nov 17, 2018
4aba3f8
BUG-23744 fix import lint
JustinZhengBC Nov 17, 2018
bcdf01b
BUG-23744 fix test
JustinZhengBC Nov 17, 2018
79be557
merge
JustinZhengBC Nov 18, 2018
99c8796
BUG-23744 move test and avoid inefficiency
JustinZhengBC Nov 19, 2018
0868c47
Merge master
JustinZhengBC Nov 23, 2018
de0ecf3
BUG-23744 make requested changes
JustinZhengBC Nov 23, 2018
491b908
BUG-23744 make requested changes
JustinZhengBC Nov 23, 2018
f6230f6
Merge branch 'BUG-23744' of https://github.com/justinzhengbc/pandas i…
JustinZhengBC Nov 23, 2018
42ca43a
Merge branch 'BUG-23744' of https://github.com/justinzhengbc/pandas i…
JustinZhengBC Nov 23, 2018
ee2c462
Merge branch 'BUG-23744' of https://github.com/justinzhengbc/pandas i…
JustinZhengBC Nov 23, 2018
bca539f
BUG-23744 use list comprehension
JustinZhengBC Nov 23, 2018
d8670ef
BUG-23744 use for loop instead
JustinZhengBC Nov 23, 2018
30d83a6
Merge branch 'master' into BUG-23744
JustinZhengBC Nov 24, 2018
c15afe3
BUG-23744 fix test
JustinZhengBC Nov 24, 2018
b4ab44b
BUG-23744 fix other test
JustinZhengBC Nov 24, 2018
d153f74
BUG-23744 use constructor properly
JustinZhengBC Nov 25, 2018
d6e22a8
BUG-23744 use block apply
JustinZhengBC Nov 26, 2018
8f151dc
BUG-23744 clarify test
JustinZhengBC Nov 27, 2018
be8750f
BUG-23744 clarify test
JustinZhengBC Nov 27, 2018
551ced8
Merge branch 'BUG-23744' of https://github.com/justinzhengbc/pandas i…
JustinZhengBC Nov 27, 2018
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/v0.24.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1460,6 +1460,7 @@ Sparse
- Bug in unary inversion operator (``~``) on a ``SparseSeries`` with boolean values. The performance of this has also been improved (:issue:`22835`)
- Bug in :meth:`SparseArary.unique` not returning the unique values (:issue:`19595`)
- Bug in :meth:`SparseArray.nonzero` and :meth:`SparseDataFrame.dropna` returning shifted/incorrect results (:issue:`21172`)
- Bug in :meth:`DataFrame.apply` where dtypes would lose sparseness (:issue:`23744`)

Build Changes
^^^^^^^^^^^^^
Expand All @@ -1486,4 +1487,3 @@ Contributors
~~~~~~~~~~~~

.. contributors:: v0.23.4..HEAD

12 changes: 11 additions & 1 deletion pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pandas.util._decorators import cache_readonly

from pandas.core.dtypes.common import (
is_dict_like, is_extension_type, is_list_like, is_sequence)
is_dict_like, is_extension_type, is_list_like, is_sequence, is_sparse)
from pandas.core.dtypes.generic import ABCSeries

from pandas.io.formats.printing import pprint_thing
Expand Down Expand Up @@ -131,6 +131,16 @@ def get_result(self):

# ufunc
elif isinstance(self.f, np.ufunc):
if any(is_sparse(dtype) for dtype in self.obj.dtypes):
# Column-by-column construction is slow, so only use when
# necessary (e.g. to preserve special dtypes) GH 23744
result = self.obj._constructor(index=self.index,
copy=False)
with np.errstate(all='ignore'):
Copy link
Contributor

Choose a reason for hiding this comment

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

this is going to be very inefficient. use a list comprehension to iterate over the columns, then collect and contruct the result. something like

def f(c):
    with np.errstate(all='ignore'):
       return self.f(c.value)

results = [f(c) for col, c for self.obj.iteritems()]
return self._constructor(results, index=self.index, columns=self.columns, copy=False)

iterate thru the series and construct the result. construct a dict instead with the results, then do the construction at the end.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

When given a list of series, the DataFrame constructor converts them all to arrays, so the columns can't all be passed into the constructor at once. To prevent inefficient constructing in the common non-sparse case, how about checking whether there are sparse columns at all, and if there are then the construction happens column-by-column but if there aren't then it does what it did before?

Copy link
Contributor

Choose a reason for hiding this comment

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

We need to be careful here. Previously, for a homogenous DataFrame of non-extension array values, df.apply(ufunc) would result in one call to the ufunc.

If we go columnwise, we'll have n calls to the ufunc.

Should this be done block-wise and then the results stitched together?

for col in self.columns:
result[col] = self.f(self.obj[col].values)
return result
Copy link
Contributor

Choose a reason for hiding this comment

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

as i said above, don't construct an empty Dataframe, rather use a dictionary (or just a list comprehension), then construct the dataframe from it right before return.

Copy link
Contributor Author

@JustinZhengBC JustinZhengBC Nov 23, 2018

Choose a reason for hiding this comment

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

Edit: just figured out I could pass a dict into the constructor to get the proper behaviour. Please disregard the rest of this post.

@jreback I can't use the constructor in that case because it stacks a list of series horizontally and there's no axis option. so I used pd.concat. Is that okay?

>>> import pandas as pd
>>> s1 = pd.Series([1, 2])
>>> s2 = pd.Series([3, 4])
>>> pd.DataFrame([s1, s2])
   0  1
0  1  2
1  3  4


with np.errstate(all='ignore'):
results = self.f(self.values)
return self.obj._constructor(data=results, index=self.index,
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/sparse/frame/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,14 @@ def test_applymap(frame):
# just test that it works
result = frame.applymap(lambda x: x * 2)
assert isinstance(result, SparseDataFrame)


def test_apply_keep_sparse_dtype():
# GH 23744
expected = SparseDataFrame(np.array([[0, 1, 0], [0, 0, 0], [0, 0, 1]]),
Copy link
Contributor

Choose a reason for hiding this comment

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

can you call this sdf. I find the repeated assignments slightly confusing here.

columns=['a', 'b', 'c'], default_fill_value=1)
result = DataFrame(expected)

expected = expected.apply(np.exp)
Copy link
Contributor

Choose a reason for hiding this comment

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

expected = sdft.apply(...)

result = result.apply(np.exp)
tm.assert_frame_equal(expected, result)