Skip to content

BUG: GH36212 DataFrame agg() raises error when DataFrame column name is name #36224

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 10 commits into from
Sep 13, 2020
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ Reshaping
- 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`)
- Bug in :func:`union_indexes` where input index names are not preserved in some cases. Affects :func:`concat` and :class:`DataFrame` constructor (:issue:`13475`)
- Bug in func :meth:`crosstab` when using multiple columns with ``margins=True`` and ``normalize=True`` (:issue:`35144`)
- Bug in :meth:`DataFrame.agg` with ``func={'name':<FUNC>}`` incorrectly raising ``TypeError`` when ``DataFrame.columns==['Name']`` (:issue:`36212`)
-

Sparse
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,9 +470,12 @@ def is_any_frame() -> bool:
try:
result = DataFrame(result)
except ValueError:

# we have a dict of scalars
result = Series(result, name=getattr(self, "name", None))

# GH 36212 use name only if self is a series
name = self.name if (self.ndim == 1) else None

result = Series(result, name=name)

return result, True
elif is_list_like(arg):
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/frame/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1147,6 +1147,21 @@ def test_demo(self):
)
tm.assert_frame_equal(result.reindex_like(expected), expected)

def test_agg_with_name_as_column_name(self):
# GH 36212 - Column name is "name"
data = {"name": ["foo", "bar"]}
df = pd.DataFrame(data)

# result's name should be None
result = df.agg({"name": "count"})
expected = pd.Series({"name": 2})
tm.assert_series_equal(result, expected)

# Check if name is still preserved when aggregating series instead
result = df["name"].agg({"name": "count"})
expected = pd.Series({"name": 2}, name="name")
tm.assert_series_equal(result, expected)

def test_agg_multiple_mixed_no_warning(self):
# GH 20909
mdf = pd.DataFrame(
Expand Down