Skip to content

TST: Test pivot_table() with categorical data #28803

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
Oct 12, 2019
Merged
Changes from 6 commits
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
43 changes: 43 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1656,6 +1656,49 @@ def test_categorical_margins_category(self, observed):
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
tm.assert_frame_equal(table, expected)

def test_pivot_with_categorical(self, observed, ordered_fixture):
# gh-21370
idx = [np.nan, "low", "high", "low", np.nan]
Copy link
Contributor

Choose a reason for hiding this comment

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

you are not using observed here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jreback Do you mean pass as keyword arg to pivot_table() ? Ive just pushed changes

col = [np.nan, "A", "B", np.nan, "A"]
df = pd.DataFrame(
{
"In": pd.Categorical(
idx, categories=["low", "high"], ordered=ordered_fixture
),
"Col": pd.Categorical(
col, categories=["A", "B"], ordered=ordered_fixture
),
"Val": range(1, 6),
}
)
# case with index/columns/value
result = df.pivot_table(index="In", columns="Col", values="Val")

expected_cols = pd.CategoricalIndex(
["A", "B"], ordered=ordered_fixture, name="Col"
)

expected = pd.DataFrame(
data=[[2.0, np.nan], [np.nan, 3.0]], columns=expected_cols
)
expected.index = Index(
pd.Categorical(
["low", "high"], categories=["low", "high"], ordered=ordered_fixture
),
name="In",
)

tm.assert_frame_equal(result, expected)

# case with columns/value
result = df.pivot_table(columns="Col", values="Val")

expected = pd.DataFrame(
data=[[3.5, 3.0]], columns=expected_cols, index=Index(["Val"])
)

tm.assert_frame_equal(result, expected)

def test_categorical_aggfunc(self, observed):
# GH 9534
df = pd.DataFrame(
Expand Down