Skip to content

Commit 56b2fd8

Browse files
ryankarlosjreback
authored andcommitted
TST: Test pivot_table() with categorical data (#28803)
1 parent 1e92886 commit 56b2fd8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

pandas/tests/reshape/test_pivot.py

+45
Original file line numberDiff line numberDiff line change
@@ -1656,6 +1656,51 @@ def test_categorical_margins_category(self, observed):
16561656
table = df.pivot_table("x", "y", "z", dropna=observed, margins=True)
16571657
tm.assert_frame_equal(table, expected)
16581658

1659+
def test_pivot_with_categorical(self, observed, ordered_fixture):
1660+
# gh-21370
1661+
idx = [np.nan, "low", "high", "low", np.nan]
1662+
col = [np.nan, "A", "B", np.nan, "A"]
1663+
df = pd.DataFrame(
1664+
{
1665+
"In": pd.Categorical(
1666+
idx, categories=["low", "high"], ordered=ordered_fixture
1667+
),
1668+
"Col": pd.Categorical(
1669+
col, categories=["A", "B"], ordered=ordered_fixture
1670+
),
1671+
"Val": range(1, 6),
1672+
}
1673+
)
1674+
# case with index/columns/value
1675+
result = df.pivot_table(
1676+
index="In", columns="Col", values="Val", observed=observed
1677+
)
1678+
1679+
expected_cols = pd.CategoricalIndex(
1680+
["A", "B"], ordered=ordered_fixture, name="Col"
1681+
)
1682+
1683+
expected = pd.DataFrame(
1684+
data=[[2.0, np.nan], [np.nan, 3.0]], columns=expected_cols
1685+
)
1686+
expected.index = Index(
1687+
pd.Categorical(
1688+
["low", "high"], categories=["low", "high"], ordered=ordered_fixture
1689+
),
1690+
name="In",
1691+
)
1692+
1693+
tm.assert_frame_equal(result, expected)
1694+
1695+
# case with columns/value
1696+
result = df.pivot_table(columns="Col", values="Val", observed=observed)
1697+
1698+
expected = pd.DataFrame(
1699+
data=[[3.5, 3.0]], columns=expected_cols, index=Index(["Val"])
1700+
)
1701+
1702+
tm.assert_frame_equal(result, expected)
1703+
16591704
def test_categorical_aggfunc(self, observed):
16601705
# GH 9534
16611706
df = pd.DataFrame(

0 commit comments

Comments
 (0)