Skip to content

Commit ed45390

Browse files
author
Marco Gorelli
committed
fix bug which prevented .apply to being called with function which returned list
1 parent 761bceb commit ed45390

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

doc/source/whatsnew/v1.0.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ including other versions of pandas.
1515

1616
Bug fixes
1717
~~~~~~~~~
18-
18+
- bug ``Groupby.apply`` was returning ``TypeError`` if called with TypeError if called with `lambda x: x.index.to_list()` (:issue:`31441`)
1919

2020
Categorical
2121
^^^^^^^^^^^

pandas/_libs/reduction.pyx

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from copy import copy
1+
from copy import copy, deepcopy
22
from distutils.version import LooseVersion
33

44
from cython import Py_ssize_t
@@ -499,7 +499,9 @@ def apply_frame_axis0(object frame, object f, object names,
499499
# `piece` might not have an index, could be e.g. an int
500500
pass
501501

502-
if not is_scalar(piece):
502+
if isinstance(piece, list):
503+
piece = deepcopy(piece)
504+
elif not is_scalar(piece):
503505
# Need to copy data to avoid appending references
504506
if hasattr(piece, "copy"):
505507
piece = piece.copy(deep="all")

pandas/tests/groupby/test_apply.py

+7
Original file line numberDiff line numberDiff line change
@@ -827,3 +827,10 @@ def test_apply_index_has_complex_internals(index):
827827
df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index)
828828
result = df.groupby("group").apply(lambda x: x)
829829
tm.assert_frame_equal(result, df)
830+
831+
832+
def test_apply_function_returns_list():
833+
df = pd.DataFrame(["A", "A", "B", "B"], columns=["groups"])
834+
result = df.groupby("groups").apply(lambda x: x.index.to_list())
835+
expected = pd.Series([[0, 1], [2, 3]], index=pd.Index(["A", "B"], name="groups"))
836+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)