Skip to content

BUG: Groupby.apply wasn't allowing for functions which return lists #31456

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 13 commits into from
Feb 1, 2020
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ including other versions of pandas.

Bug fixes
~~~~~~~~~

- Bug in :meth:`GroupBy.apply` was raising ``TypeError`` if called with function which returned list (:issue:`31441`)

Categorical
^^^^^^^^^^^
Expand Down
3 changes: 1 addition & 2 deletions pandas/_libs/reduction.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -500,8 +500,7 @@ def apply_frame_axis0(object frame, object f, object names,
pass

if not is_scalar(piece):
# Need to copy data to avoid appending references
if hasattr(piece, "copy"):
if hasattr(piece, "_typ") and piece._typ == "series":
piece = piece.copy(deep="all")
else:
piece = copy(piece)
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -827,3 +827,11 @@ def test_apply_index_has_complex_internals(index):
df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index)
result = df.groupby("group").apply(lambda x: x)
tm.assert_frame_equal(result, df)


def test_apply_function_returns_list():
# GH 31441
df = pd.DataFrame(["A", "A", "B", "B"], columns=["groups"])
result = df.groupby("groups").apply(lambda x: x.index.to_list())
Copy link
Member

Choose a reason for hiding this comment

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

Might be good to add tests for other return types as well (e.g., set or tuple)

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, good suggestion, thanks!

expected = pd.Series([[0, 1], [2, 3]], index=pd.Index(["A", "B"], name="groups"))
tm.assert_series_equal(result, expected)