Skip to content

TST: Add tests for MultiIndex columns cases in aggregate relabelling #29504

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 9 commits into from
Nov 13, 2019
64 changes: 64 additions & 0 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,70 @@ def test_mangled(self):
tm.assert_frame_equal(result, expected)


def test_agg_relabel_multiindex_column():
# GH 29422, add tests for multiindex column cases
df = DataFrame(
{"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]}
)
df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")])
idx = pd.Index(["a", "b"], name=("x", "group"))

result = df.groupby(("x", "group")).agg(a_max=(("y", "A"), "max"))
expected = DataFrame({"a_max": [1, 3]}, index=idx)
tm.assert_frame_equal(result, expected)

# multiple columns, and different agg methods
result = df.groupby(("x", "group")).agg(
a_max=(("y", "A"), "max"),
a_min=(("y", "A"), np.min),
b_mean=(("y", "B"), "mean"),
)
expected = DataFrame(
{"a_max": [1, 3], "a_min": [0, 2], "b_mean": [5.5, 7.5]}, index=idx
)
tm.assert_frame_equal(result, expected)

# multiple colums, with lamdba being used
result = df.groupby(("x", "group")).agg(
a_max=(("y", "A"), lambda x: max(x)),
a_const=(("y", "A"), lambda x: 1),
b_mean=(("y", "B"), "mean"),
)
expected = DataFrame(
{"a_max": [1, 3], "a_const": [1, 1], "b_mean": [5.5, 7.5]}, index=idx
)
tm.assert_frame_equal(result, expected)


def test_agg_relabel_multiindex_raises():
# GH 29422, add tests for raises senarios in multiindex column cases
df = DataFrame(
{"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]}
)
df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")])

with pytest.raises(KeyError, match="does not exist"):
df.groupby(("x", "group")).agg(a=(("Y", "a"), "max"))

with pytest.raises(SpecificationError, match="Function names"):
df.groupby(("x", "group")).agg(a=(("y", "A"), "min"), b=(("y", "A"), "min"))


def test_named_agg_multiindex_column():
# GH 29422, add tests for namedagg in multiindex column cases
df = DataFrame(
{"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]}
)
df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")])
idx = pd.Index(["a", "b"], name=("x", "group"))

result = df.groupby(("x", "group")).agg(
a_max=pd.NamedAgg(("y", "A"), "max"), b_mean=pd.NamedAgg(("y", "B"), np.mean)
)
expected = DataFrame({"a_max": [1, 3], "b_mean": [5.5, 7.5]}, index=idx)
tm.assert_frame_equal(result, expected)


def myfunc(s):
return np.percentile(s, q=0.90)

Expand Down