Skip to content

BUG/TST: Address GH28283 calling __finalize__ in pivot_table, groupby.median and groupby.mean #39473

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
Feb 20, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ Reshaping
- Bug in :meth:`DataFrame.join` not assigning values correctly when having :class:`MultiIndex` where at least one dimension is from dtype ``Categorical`` with non-alphabetically sorted categories (:issue:`38502`)
- :meth:`Series.value_counts` returns keys in original order (:issue:`12679`, :issue:`11227`)
- Bug in :meth:`DataFrame.apply` would give incorrect results when used with a string argument and ``axis=1`` when the axis argument was not supported and now raises a ``ValueError`` instead (:issue:`39211`)
-
- Bug in :meth:`.GroupBy.mean`, :meth:`.GroupBy.median` and :meth:`DataFrame.pivot_table` not propagating metadata (:issue:`28283`)

Sparse
^^^^^^
Expand Down
6 changes: 4 additions & 2 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1513,11 +1513,12 @@ def mean(self, numeric_only: bool = True):
2 4.0
Name: B, dtype: float64
"""
return self._cython_agg_general(
result = self._cython_agg_general(
"mean",
alt=lambda x, axis: Series(x).mean(numeric_only=numeric_only),
numeric_only=numeric_only,
)
return result.__finalize__(self.obj, method="groupby")

@final
@Substitution(name="groupby")
Expand All @@ -1539,11 +1540,12 @@ def median(self, numeric_only=True):
Series or DataFrame
Median of values within each group.
"""
return self._cython_agg_general(
result = self._cython_agg_general(
"median",
alt=lambda x, axis: Series(x).median(axis=axis, numeric_only=numeric_only),
numeric_only=numeric_only,
)
return result.__finalize__(self.obj, method="groupby")

@final
@Substitution(name="groupby")
Expand Down
35 changes: 32 additions & 3 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def pivot_table(
pieces: List[DataFrame] = []
keys = []
for func in aggfunc:
table = pivot_table(
_table = _pivot_table(
data,
values=values,
index=index,
Expand All @@ -70,10 +70,39 @@ def pivot_table(
margins_name=margins_name,
observed=observed,
)
pieces.append(table)
pieces.append(_table)
keys.append(getattr(func, "__name__", func))

return concat(pieces, keys=keys, axis=1)
table = concat(pieces, keys=keys, axis=1)
return table.__finalize__(data, method="pivot_table")

table = _pivot_table(
Copy link
Contributor

Choose a reason for hiding this comment

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

this is way more complicated to read. need to simplify this or have a better name for _pivot_table -> __internal_pivot_table, and add a doc-string & types.

Copy link
Contributor

Choose a reason for hiding this comment

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

this maybe worth reverting and doing in a dedicated PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Just finished reading the requirements for doc-string. Will rename the function and add a doc-string & types.

data,
values,
index,
columns,
aggfunc,
fill_value,
margins,
dropna,
margins_name,
observed,
)
return table.__finalize__(data, method="pivot_table")


def _pivot_table(
data,
values,
index,
columns,
aggfunc: str,
fill_value,
margins,
dropna,
margins_name,
observed,
) -> DataFrame:

keys = index + columns

Expand Down
24 changes: 17 additions & 7 deletions pandas/tests/generic/test_finalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,15 @@
marks=not_implemented_mark,
),
(pd.DataFrame, frame_data, operator.methodcaller("pivot", columns="A")),
pytest.param(
(
pd.DataFrame,
{"A": [1], "B": [1]},
operator.methodcaller("pivot_table", columns="A"),
),
marks=not_implemented_mark,
(
pd.DataFrame,
({"A": [1], "B": [1]},),
operator.methodcaller("pivot_table", columns="A"),
),
(
pd.DataFrame,
({"A": [1], "B": [1]},),
operator.methodcaller("pivot_table", columns="A", aggfunc=["mean", "sum"]),
),
(pd.DataFrame, frame_data, operator.methodcaller("stack")),
pytest.param(
Expand Down Expand Up @@ -740,6 +742,8 @@ def test_categorical_accessor(method):
[
operator.methodcaller("sum"),
lambda x: x.agg("sum"),
lambda x: x.agg("mean"),
lambda x: x.agg("median"),
],
)
def test_groupby_finalize(obj, method):
Expand All @@ -757,6 +761,12 @@ def test_groupby_finalize(obj, method):
lambda x: x.agg(["sum", "count"]),
lambda x: x.transform(lambda y: y),
lambda x: x.apply(lambda y: y),
lambda x: x.agg("std"),
lambda x: x.agg("var"),
lambda x: x.agg("sem"),
lambda x: x.agg("size"),
lambda x: x.agg("ohlc"),
lambda x: x.agg("describe"),
],
)
@not_implemented_mark
Expand Down