Skip to content

BUG: Break reference from grouping level to MI #31133

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 4 commits into from
Jan 20, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1235,6 +1235,9 @@ def _set_names(self, names, level=None, validate=True):
def _get_grouper_for_level(self, mapper, level):
indexer = self.codes[level]
level_index = self.levels[level]
# break references back to ourself so that setting the name
# on the output of a groupby doesn't reflect back here.
level_index = level_index.copy()
Copy link
Contributor

Choose a reason for hiding this comment

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

you don't need to do this here, rather do it as an else on line 1261 (add it); as take already copies, its just when that condition is not satisfied does it need a copy.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed, I think. Added a case for Categorical grouper with unobserved categories, so I think all the cases are covered.


if mapper is not None:
# Handle group mapping function and return
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,3 +752,21 @@ def most_common_values(df):
["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"
)
tm.assert_series_equal(result, expected)


def test_apply_multi_level_name():
# https://github.com/pandas-dev/pandas/issues/31068
df = pd.DataFrame(
{
"A": np.arange(10),
"B": [1, 2] * 5,
"C": list(range(10)),
"D": list(range(10)),
}
).set_index(["A", "B"])
result = df.groupby("B").apply(lambda x: x.sum())
expected = pd.DataFrame(
{"C": [20, 25], "D": [20, 25]}, index=pd.Index([1, 2], name="B")
)
tm.assert_frame_equal(result, expected)
assert df.index.names == ["A", "B"]