@@ -2554,3 +2554,28 @@ def test_margin_normalize(self):
2554
2554
names = ["A" , "B" ],
2555
2555
)
2556
2556
tm .assert_frame_equal (result , expected )
2557
+
2558
+ def test_pivot_with_categorical (self , dropna ):
2559
+ # gh-21370
2560
+ idx = [np .nan , "low" , "high" , "low" , np .nan ]
2561
+ col = [np .nan , "A" , "B" , np .nan , "A" ]
2562
+ df = pd .DataFrame (
2563
+ {
2564
+ "In" : pd .Categorical (idx , categories = ["low" , "high" ], ordered = True ),
2565
+ "Col" : pd .Categorical (col , categories = ["A" , "B" ], ordered = True ),
2566
+ "Val" : range (1 , 6 ),
2567
+ }
2568
+ )
2569
+ result = df .pivot_table (index = "In" , columns = "Col" , values = "Val" )
2570
+
2571
+ expected_cols = pd .CategoricalIndex (["A" , "B" ], ordered = True , name = "Col" )
2572
+
2573
+ expected = pd .DataFrame (
2574
+ data = [[2.0 , np .nan ], [np .nan , 3.0 ]], columns = expected_cols
2575
+ )
2576
+ expected .index = Index (
2577
+ pd .Categorical (["low" , "high" ], categories = ["low" , "high" ], ordered = True ),
2578
+ name = "In" ,
2579
+ )
2580
+
2581
+ tm .assert_frame_equal (result , expected )
0 commit comments