Skip to content
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

ENH: Groupby.transform support string input with engine=numba #53579

Merged
merged 4 commits into from
Jun 12, 2023
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/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Other enhancements
- :meth:`DataFrame.unstack` gained the ``sort`` keyword to dictate whether the resulting :class:`MultiIndex` levels are sorted (:issue:`15105`)
- :meth:`DataFrameGroupby.agg` and :meth:`DataFrameGroupby.transform` now support grouping by multiple keys when the index is not a :class:`MultiIndex` for ``engine="numba"`` (:issue:`53486`)
- :meth:`SeriesGroupby.agg` and :meth:`DataFrameGroupby.agg` now support passing in multiple functions for ``engine="numba"`` (:issue:`53486`)
- :meth:`SeriesGroupby.transform` and :meth:`DataFrameGroupby.transform` now support passing in a string as the function for ``engine="numba"`` (:issue:`53579`)
- Added ``engine_kwargs`` parameter to :meth:`DataFrame.to_excel` (:issue:`53220`)
- Added a new parameter ``by_row`` to :meth:`Series.apply`. When set to ``False`` the supplied callables will always operate on the whole Series (:issue:`53400`).
- Many read/to_* functions, such as :meth:`DataFrame.to_pickle` and :func:`read_csv`, support forwarding compression arguments to lzma.LZMAFile (:issue:`52979`)
Expand Down
14 changes: 12 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,10 +523,16 @@ def _cython_transform(

return obj._constructor(result, index=self.obj.index, name=obj.name)

def _transform_general(self, func: Callable, *args, **kwargs) -> Series:
def _transform_general(
self, func: Callable, engine, engine_kwargs, *args, **kwargs
) -> Series:
"""
Transform with a callable `func`.
"""
if maybe_use_numba(engine):
return self._transform_with_numba(
func, *args, engine_kwargs=engine_kwargs, **kwargs
)
assert callable(func)
klass = type(self.obj)

Expand Down Expand Up @@ -1654,7 +1660,11 @@ def arr_func(bvalues: ArrayLike) -> ArrayLike:
res_df = self._maybe_transpose_result(res_df)
return res_df

def _transform_general(self, func, *args, **kwargs):
def _transform_general(self, func, engine, engine_kwargs, *args, **kwargs):
if maybe_use_numba(engine):
return self._transform_with_numba(
func, *args, engine_kwargs=engine_kwargs, **kwargs
)
from pandas.core.reshape.concat import concat

applied = []
Expand Down
13 changes: 7 additions & 6 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1787,22 +1787,20 @@ def _cython_transform(

@final
def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
if maybe_use_numba(engine):
return self._transform_with_numba(
func, *args, engine_kwargs=engine_kwargs, **kwargs
)

# optimized transforms
func = com.get_cython_func(func) or func

if not isinstance(func, str):
return self._transform_general(func, *args, **kwargs)
return self._transform_general(func, engine, engine_kwargs, *args, **kwargs)

elif func not in base.transform_kernel_allowlist:
msg = f"'{func}' is not a valid function name for transform(name)"
raise ValueError(msg)
elif func in base.cythonized_kernels or func in base.transformation_kernels:
# cythonized transform or canned "agg+broadcast"
if engine is not None:
Copy link
Member Author

Choose a reason for hiding this comment

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

Since there are no transformation kernels(e.g. cumsum, shift etc.) for numba yet, this is untested.

Should be OK, though, since this didn't work before anyways.

Copy link
Member

Choose a reason for hiding this comment

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

Curious, what type of error do we get when we pass engine="cython", engine_kwargs={"nogil": True}?

Copy link
Member Author

Choose a reason for hiding this comment

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

IIRC, it gives something like

Groupby.method() got an unexpected argument engine

kwargs["engine"] = engine
kwargs["engine_kwargs"] = engine_kwargs
return getattr(self, func)(*args, **kwargs)

else:
Expand All @@ -1817,6 +1815,9 @@ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
with com.temp_setattr(self, "as_index", True):
# GH#49834 - result needs groups in the index for
# _wrap_transform_fast_result
if engine is not None:
kwargs["engine"] = engine
kwargs["engine_kwargs"] = engine_kwargs
result = getattr(self, func)(*args, **kwargs)

return self._wrap_transform_fast_result(result)
Expand Down
18 changes: 10 additions & 8 deletions pandas/tests/groupby/transform/test_numba.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,20 +130,25 @@ def func_1(values, index):
tm.assert_frame_equal(expected, result)


# TODO: Test more than just reductions (e.g. actually test transformations once we have
@td.skip_if_no("numba")
@pytest.mark.parametrize(
"agg_func", [["min", "max"], "min", {"B": ["min", "max"], "C": "sum"}]
)
def test_multifunc_notimplimented(agg_func):
Copy link
Member Author

Choose a reason for hiding this comment

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

Had to change the test since multifuncs (list/dicts of funcs) aren't supported anyways in transform for the cython engine as well.

def test_string_cython_vs_numba(agg_func, numba_supported_reductions):
agg_func, kwargs = numba_supported_reductions
data = DataFrame(
{0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1]
)
grouped = data.groupby(0)
with pytest.raises(NotImplementedError, match="Numba engine can"):
grouped.transform(agg_func, engine="numba")

with pytest.raises(NotImplementedError, match="Numba engine can"):
grouped[1].transform(agg_func, engine="numba")
result = grouped.transform(agg_func, engine="numba", **kwargs)
expected = grouped.transform(agg_func, engine="cython", **kwargs)
tm.assert_frame_equal(result, expected)

result = grouped[1].transform(agg_func, engine="numba", **kwargs)
expected = grouped[1].transform(agg_func, engine="cython", **kwargs)
tm.assert_series_equal(result, expected)


@td.skip_if_no("numba")
Expand Down Expand Up @@ -232,9 +237,6 @@ def numba_func(values, index):


@td.skip_if_no("numba")
@pytest.mark.xfail(
reason="Groupby transform doesn't support strings as function inputs yet with numba"
)
def test_multilabel_numba_vs_cython(numba_supported_reductions):
reduction, kwargs = numba_supported_reductions
df = DataFrame(
Expand Down