Skip to content

Commit 068d1b5

Browse files
BUG: GH36212 DataFrame agg() raises error when DataFrame column name is name (#36224)
1 parent 65074db commit 068d1b5

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

doc/source/whatsnew/v1.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ Reshaping
327327
- Bug in :meth:`DataFrame.pivot_table` with ``aggfunc='count'`` or ``aggfunc='sum'`` returning ``NaN`` for missing categories when pivoted on a ``Categorical``. Now returning ``0`` (:issue:`31422`)
328328
- Bug in :func:`union_indexes` where input index names are not preserved in some cases. Affects :func:`concat` and :class:`DataFrame` constructor (:issue:`13475`)
329329
- Bug in func :meth:`crosstab` when using multiple columns with ``margins=True`` and ``normalize=True`` (:issue:`35144`)
330+
- Bug in :meth:`DataFrame.agg` with ``func={'name':<FUNC>}`` incorrectly raising ``TypeError`` when ``DataFrame.columns==['Name']`` (:issue:`36212`)
330331
-
331332

332333
Sparse

pandas/core/base.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -470,9 +470,12 @@ def is_any_frame() -> bool:
470470
try:
471471
result = DataFrame(result)
472472
except ValueError:
473-
474473
# we have a dict of scalars
475-
result = Series(result, name=getattr(self, "name", None))
474+
475+
# GH 36212 use name only if self is a series
476+
name = self.name if (self.ndim == 1) else None
477+
478+
result = Series(result, name=name)
476479

477480
return result, True
478481
elif is_list_like(arg):

pandas/tests/frame/apply/test_frame_apply.py

+15
Original file line numberDiff line numberDiff line change
@@ -1147,6 +1147,21 @@ def test_demo(self):
11471147
)
11481148
tm.assert_frame_equal(result.reindex_like(expected), expected)
11491149

1150+
def test_agg_with_name_as_column_name(self):
1151+
# GH 36212 - Column name is "name"
1152+
data = {"name": ["foo", "bar"]}
1153+
df = pd.DataFrame(data)
1154+
1155+
# result's name should be None
1156+
result = df.agg({"name": "count"})
1157+
expected = pd.Series({"name": 2})
1158+
tm.assert_series_equal(result, expected)
1159+
1160+
# Check if name is still preserved when aggregating series instead
1161+
result = df["name"].agg({"name": "count"})
1162+
expected = pd.Series({"name": 2}, name="name")
1163+
tm.assert_series_equal(result, expected)
1164+
11501165
def test_agg_multiple_mixed_no_warning(self):
11511166
# GH 20909
11521167
mdf = pd.DataFrame(

0 commit comments

Comments
 (0)