Skip to content
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

TST: add test for agg on ordered categorical cols #35630

Merged
merged 6 commits into from
Aug 21, 2020
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
34 changes: 34 additions & 0 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,3 +1061,37 @@ def test_groupby_get_by_index():
res = df.groupby("A").agg({"B": lambda x: x.get(x.index[-1])})
expected = pd.DataFrame(dict(A=["S", "W"], B=[1.0, 2.0])).set_index("A")
pd.testing.assert_frame_equal(res, expected)


def test_groupby_agg_categorical_cols():
"""
Copy link
Contributor

Choose a reason for hiding this comment

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

pls add the issue number as a comment.

you don't really need the doc-string; the test name should be descriptive enough

test aggregation on ordered categorical
columns #27800
"""

# create the result dataframe
input_df = pd.DataFrame(
{
"nr": [1, 2, 3, 4, 5, 6, 7, 8],
"cat_ord": list("aabbccdd"),
"cat": list("aaaabbbb"),
}
)

input_df = input_df.astype({"cat": "category", "cat_ord": "category"})
input_df["cat_ord"] = input_df["cat_ord"].cat.as_ordered()
result_df = input_df.groupby("cat").agg({"nr": ["min", "max"], "cat_ord": "min"})

# create expected dataframe
cat_index = pd.CategoricalIndex(
["a", "b"], categories=["a", "b"], ordered=False, name="cat", dtype="category"
)

multi_index_tuple = [("nr", "min"), ("nr", "max"), ("cat_ord", "min")]
multi_index = pd.MultiIndex.from_tuples(multi_index_tuple)

data = np.array([(1, 4, "a"), (5, 8, "c")])
Copy link
Member

Choose a reason for hiding this comment

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

I think if you just pass this in as a list, then you won't have to astype() later on

expected_df = pd.DataFrame(data=data, columns=multi_index, index=cat_index)
expected_df["nr"] = expected_df["nr"].astype("int64")

tm.assert_frame_equal(result_df, expected_df)