Skip to content

BUG: agg with dictlike and non-unique col will return wrong type #52115

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 18 commits into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1371,6 +1371,7 @@ Reshaping
- Bug in :meth:`DataFrame.explode` raising ``ValueError`` on multiple columns with ``NaN`` values or empty lists (:issue:`46084`)
- Bug in :meth:`DataFrame.transpose` with ``IntervalDtype`` column with ``timedelta64[ns]`` endpoints (:issue:`44917`)
- Bug in :meth:`DataFrame.agg` and :meth:`Series.agg` would ignore arguments when passed a list of functions (:issue:`50863`)
- Bug in :meth:`DataFrame.agg` and :meth:`Series.agg` on non-unique columns would return incorrect type when dist-like argument passed in (:issue:`51099`)

Sparse
^^^^^^
Expand Down
35 changes: 30 additions & 5 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,17 +410,32 @@ def agg_dict_like(self) -> DataFrame | Series:
context_manager = com.temp_setattr(obj, "as_index", True)
else:
context_manager = nullcontext()

if isinstance(selected_obj, ABCDataFrame):
is_non_unique_col = selected_obj.columns.duplicated().tolist()
else:
is_non_unique_col = [False]

with context_manager:
if selected_obj.ndim == 1:
# key only used for output
colg = obj._gotitem(selection, ndim=1)
results = {key: colg.agg(how) for key, how in arg.items()}
key_res = obj._gotitem(selection, ndim=1)
results = {key: key_res.agg(how) for key, how in arg.items()}
elif any(is_non_unique_col):
# GH#51099
# results is a dict of lists
results = {}
for key, how in arg.items():
key_res = []
for col_idx in selected_obj.columns.get_indexer_for([key]):
col = selected_obj.iloc[:, col_idx]
key_res.append(col.agg(how))
results[key] = key_res
else:
# key used for column selection and output
results = {
key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items()
}

# set the final keys
keys = list(arg.keys())

Expand Down Expand Up @@ -455,15 +470,25 @@ def agg_dict_like(self) -> DataFrame | Series:
else:
from pandas import Series

# we have a dict of scalars
# we have a dict of scalars or a list of scalars
# GH 36212 use name only if obj is a series
if obj.ndim == 1:
obj = cast("Series", obj)
name = obj.name
else:
name = None

result = Series(results, name=name)
if any(is_non_unique_col):
# Expand the scalar list and construct a series.
series_list = []
for key, value in results.items():
assert isinstance(value, list)
series_list.append(Series(value, index=[key] * len(value)))

result = concat(series_list, axis=0)
result.name = name
else:
result = Series(results, name=name)

return result

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1665,3 +1665,15 @@ def foo2(x, b=2, c=0):
columns=MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]),
)
tm.assert_frame_equal(result, expected)


def test_agg_dist_like_and_nonunique_columns():
# GH#51099
df = DataFrame(
{"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]}
)
df.columns = ["A", "A", "C"]

result = df.agg({"A": "count"})
expected = df["A"].count()
tm.assert_series_equal(result, expected)