Skip to content

BUG: groupby.transform/agg caching *args with numba engine #41656

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 1 commit into from
May 26, 2021
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrameGroupBy.__getitem__` with non-unique columns incorrectly returning a malformed :class:`SeriesGroupBy` instead of :class:`DataFrameGroupBy` (:issue:`41427`)
- Bug in :meth:`DataFrameGroupBy.transform` with non-unique columns incorrectly raising ``AttributeError`` (:issue:`41427`)
- Bug in :meth:`Resampler.apply` with non-unique columns incorrectly dropping duplicated columns (:issue:`41445`)
- Bug in :meth:`DataFrameGroupBy.transform` and :meth:`DataFrameGroupBy.agg` with ``engine="numba"`` where ``*args`` were being cached with the user passed function (:issue:`41647`)

Reshaping
^^^^^^^^^
Expand Down
22 changes: 16 additions & 6 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1131,10 +1131,16 @@ def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs)
group_keys = self.grouper._get_group_keys()

numba_transform_func = numba_.generate_numba_transform_func(
tuple(args), kwargs, func, engine_kwargs
kwargs, func, engine_kwargs
Copy link
Contributor

Choose a reason for hiding this comment

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

shouldn't knwargs be handled in the same way?

Copy link
Member Author

Choose a reason for hiding this comment

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

numba doesn't support **kwargs in udf's currently. It's passed here to raise an error if kwargs is not empty

)
result = numba_transform_func(
sorted_data, sorted_index, starts, ends, len(group_keys), len(data.columns)
sorted_data,
sorted_index,
starts,
ends,
len(group_keys),
len(data.columns),
*args,
)

cache_key = (func, "groupby_transform")
Expand All @@ -1157,11 +1163,15 @@ def _aggregate_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs)
starts, ends, sorted_index, sorted_data = self._numba_prep(func, data)
group_keys = self.grouper._get_group_keys()

numba_agg_func = numba_.generate_numba_agg_func(
tuple(args), kwargs, func, engine_kwargs
)
numba_agg_func = numba_.generate_numba_agg_func(kwargs, func, engine_kwargs)
result = numba_agg_func(
sorted_data, sorted_index, starts, ends, len(group_keys), len(data.columns)
sorted_data,
sorted_index,
starts,
ends,
len(group_keys),
len(data.columns),
*args,
)

cache_key = (func, "groupby_agg")
Expand Down
16 changes: 8 additions & 8 deletions pandas/core/groupby/numba_.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,12 @@ def f(values, index, ...):


def generate_numba_agg_func(
args: tuple,
kwargs: dict[str, Any],
func: Callable[..., Scalar],
engine_kwargs: dict[str, bool] | None,
) -> Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int], np.ndarray]:
) -> Callable[
[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, Any], np.ndarray
]:
"""
Generate a numba jitted agg function specified by values from engine_kwargs.

Expand All @@ -72,8 +73,6 @@ def generate_numba_agg_func(

Parameters
----------
args : tuple
*args to be passed into the function
kwargs : dict
**kwargs to be passed into the function
func : function
Expand Down Expand Up @@ -103,6 +102,7 @@ def group_agg(
end: np.ndarray,
num_groups: int,
num_columns: int,
*args: Any,
) -> np.ndarray:
result = np.empty((num_groups, num_columns))
for i in numba.prange(num_groups):
Expand All @@ -116,11 +116,12 @@ def group_agg(


def generate_numba_transform_func(
args: tuple,
kwargs: dict[str, Any],
func: Callable[..., np.ndarray],
engine_kwargs: dict[str, bool] | None,
) -> Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int], np.ndarray]:
) -> Callable[
[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int, Any], np.ndarray
]:
"""
Generate a numba jitted transform function specified by values from engine_kwargs.

Expand All @@ -132,8 +133,6 @@ def generate_numba_transform_func(

Parameters
----------
args : tuple
*args to be passed into the function
kwargs : dict
**kwargs to be passed into the function
func : function
Expand Down Expand Up @@ -163,6 +162,7 @@ def group_transform(
end: np.ndarray,
num_groups: int,
num_columns: int,
*args: Any,
) -> np.ndarray:
result = np.empty((len(values), num_columns))
for i in numba.prange(num_groups):
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/groupby/aggregate/test_numba.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

from pandas import (
DataFrame,
Index,
NamedAgg,
Series,
option_context,
)
import pandas._testing as tm
Expand Down Expand Up @@ -154,3 +156,20 @@ def test_multifunc_notimplimented(agg_func):

with pytest.raises(NotImplementedError, match="Numba engine can"):
grouped[1].agg(agg_func, engine="numba")


@td.skip_if_no("numba", "0.46.0")
def test_args_not_cached():
# GH 41647
def sum_last(values, index, n):
return values[-n:].sum()

df = DataFrame({"id": [0, 0, 1, 1], "x": [1, 1, 1, 1]})
grouped_x = df.groupby("id")["x"]
result = grouped_x.agg(sum_last, 1, engine="numba")
expected = Series([1.0] * 2, name="x", index=Index([0, 1], name="id"))
tm.assert_series_equal(result, expected)

result = grouped_x.agg(sum_last, 2, engine="numba")
expected = Series([2.0] * 2, name="x", index=Index([0, 1], name="id"))
tm.assert_series_equal(result, expected)
18 changes: 18 additions & 0 deletions pandas/tests/groupby/transform/test_numba.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from pandas import (
DataFrame,
Series,
option_context,
)
import pandas._testing as tm
Expand Down Expand Up @@ -146,3 +147,20 @@ def test_multifunc_notimplimented(agg_func):

with pytest.raises(NotImplementedError, match="Numba engine can"):
grouped[1].transform(agg_func, engine="numba")


@td.skip_if_no("numba", "0.46.0")
def test_args_not_cached():
# GH 41647
def sum_last(values, index, n):
return values[-n:].sum()

df = DataFrame({"id": [0, 0, 1, 1], "x": [1, 1, 1, 1]})
grouped_x = df.groupby("id")["x"]
result = grouped_x.transform(sum_last, 1, engine="numba")
expected = Series([1.0] * 4, name="x")
tm.assert_series_equal(result, expected)

result = grouped_x.transform(sum_last, 2, engine="numba")
expected = Series([2.0] * 4, name="x")
tm.assert_series_equal(result, expected)