@@ -2619,9 +2619,36 @@ def test_pivot_not_changing_index_name(self):
2619
2619
tm .assert_frame_equal (df , expected )
2620
2620
2621
2621
def test_pivot_table_empty_dataframe_correct_index (self ):
2622
- # GH 21932
2622
+ # GH# 21932
2623
2623
df = DataFrame ([], columns = ["a" , "b" , "value" ])
2624
2624
pivot = df .pivot_table (index = "a" , columns = "b" , values = "value" , aggfunc = "count" )
2625
2625
2626
2626
expected = Index ([], dtype = "object" , name = "b" )
2627
2627
tm .assert_index_equal (pivot .columns , expected )
2628
+
2629
+ def test_pivot_table_handles_explicit_datetime_types (self ):
2630
+ # GH#43574
2631
+ df = DataFrame (
2632
+ [
2633
+ {"a" : "x" , "date_str" : "2023-01-01" , "amount" : 1 },
2634
+ {"a" : "y" , "date_str" : "2023-01-02" , "amount" : 2 },
2635
+ {"a" : "z" , "date_str" : "2023-01-03" , "amount" : 3 },
2636
+ ]
2637
+ )
2638
+ df ["date" ] = pd .to_datetime (df ["date_str" ])
2639
+
2640
+ with tm .assert_produces_warning (False ):
2641
+ pivot = df .pivot_table (
2642
+ index = ["a" , "date" ], values = ["amount" ], aggfunc = "sum" , margins = True
2643
+ )
2644
+
2645
+ expected = MultiIndex .from_tuples (
2646
+ [
2647
+ ("x" , datetime .strptime ("2023-01-01 00:00:00" , "%Y-%m-%d %H:%M:%S" )),
2648
+ ("y" , datetime .strptime ("2023-01-02 00:00:00" , "%Y-%m-%d %H:%M:%S" )),
2649
+ ("z" , datetime .strptime ("2023-01-03 00:00:00" , "%Y-%m-%d %H:%M:%S" )),
2650
+ ("All" , "" ),
2651
+ ],
2652
+ names = ["a" , "date" ],
2653
+ )
2654
+ tm .assert_index_equal (pivot .index , expected )
0 commit comments