Skip to content

TST: Add test for old issues #41431

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 7 commits into from
May 12, 2021
Merged
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
Prev Previous commit
Next Next commit
Add test for GH 12652
  • Loading branch information
mroeschke committed May 12, 2021
commit 6853e6d805250db5134c0749e6c12f73bea405d7
60 changes: 60 additions & 0 deletions pandas/tests/groupby/test_apply_mutate.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,63 @@ def fn(x):
name="col2",
)
tm.assert_series_equal(result, expected)


def test_apply_mutate_columns_multiindex():
# GH 12652
df = pd.DataFrame(
{
("C", "julian"): [1, 2, 3],
("B", "geoffrey"): [1, 2, 3],
("A", "julian"): [1, 2, 3],
("B", "julian"): [1, 2, 3],
("A", "geoffrey"): [1, 2, 3],
("C", "geoffrey"): [1, 2, 3],
},
columns=pd.MultiIndex.from_tuples(
[
("A", "julian"),
("A", "geoffrey"),
("B", "julian"),
("B", "geoffrey"),
("C", "julian"),
("C", "geoffrey"),
]
),
)

def add_column(grouped):
name = grouped.columns[0][1]
grouped["sum", name] = grouped.sum(axis=1)
return grouped

result = df.groupby(level=1, axis=1).apply(add_column)
expected = pd.DataFrame(
[
[1, 1, 1, 3, 1, 1, 1, 3],
[2, 2, 2, 6, 2, 2, 2, 6],
[
3,
3,
3,
9,
3,
3,
3,
9,
],
],
columns=pd.MultiIndex.from_tuples(
[
("geoffrey", "A", "geoffrey"),
("geoffrey", "B", "geoffrey"),
("geoffrey", "C", "geoffrey"),
("geoffrey", "sum", "geoffrey"),
("julian", "A", "julian"),
("julian", "B", "julian"),
("julian", "C", "julian"),
("julian", "sum", "julian"),
]
),
)
tm.assert_frame_equal(result, expected)