@@ -527,6 +527,50 @@ def test_pivot_datetime_tz(self):
527
527
aggfunc = [np .sum , np .mean ])
528
528
tm .assert_frame_equal (result , expected )
529
529
530
+ def test_pivot_dtaccessor (self ):
531
+ # GH 8103
532
+ dates1 = ['2011-07-19 07:00:00' , '2011-07-19 08:00:00' , '2011-07-19 09:00:00' ,
533
+ '2011-07-19 07:00:00' , '2011-07-19 08:00:00' , '2011-07-19 09:00:00' ]
534
+ dates2 = ['2013-01-01 15:00:00' , '2013-01-01 15:00:00' , '2013-01-01 15:00:00' ,
535
+ '2013-02-01 15:00:00' , '2013-02-01 15:00:00' , '2013-02-01 15:00:00' ]
536
+ df = DataFrame ({'label' : ['a' , 'a' , 'a' , 'b' , 'b' , 'b' ],
537
+ 'dt1' : dates1 , 'dt2' : dates2 ,
538
+ 'value1' : np .arange (6 ,dtype = 'int64' ), 'value2' : [1 , 2 ] * 3 })
539
+ df ['dt1' ] = df ['dt1' ].apply (lambda d : pd .Timestamp (d ))
540
+ df ['dt2' ] = df ['dt2' ].apply (lambda d : pd .Timestamp (d ))
541
+
542
+ result = pivot_table (df , index = 'label' , columns = df ['dt1' ].dt .hour ,
543
+ values = 'value1' )
544
+
545
+ exp_idx = Index (['a' , 'b' ], name = 'label' )
546
+ expected = DataFrame ({7 : [0 , 3 ], 8 : [1 , 4 ], 9 :[2 , 5 ]},
547
+ index = exp_idx , columns = [7 , 8 , 9 ])
548
+ tm .assert_frame_equal (result , expected )
549
+
550
+ result = pivot_table (df , index = df ['dt2' ].dt .month , columns = df ['dt1' ].dt .hour ,
551
+ values = 'value1' )
552
+
553
+ expected = DataFrame ({7 : [0 , 3 ], 8 : [1 , 4 ], 9 :[2 , 5 ]},
554
+ index = [1 , 2 ], columns = [7 , 8 , 9 ])
555
+ tm .assert_frame_equal (result , expected )
556
+
557
+ result = pivot_table (df , index = df ['dt2' ].dt .year ,
558
+ columns = [df ['dt1' ].dt .hour , df ['dt2' ].dt .month ],
559
+ values = 'value1' )
560
+
561
+ exp_col = MultiIndex .from_arrays ([[7 , 7 , 8 , 8 , 9 , 9 ], [1 , 2 ] * 3 ])
562
+ expected = DataFrame (np .array ([[0 , 3 , 1 , 4 , 2 , 5 ]]),
563
+ index = [2013 ], columns = exp_col )
564
+ tm .assert_frame_equal (result , expected )
565
+
566
+ result = pivot_table (df , index = np .array (['X' , 'X' , 'X' , 'X' , 'Y' , 'Y' ]),
567
+ columns = [df ['dt1' ].dt .hour , df ['dt2' ].dt .month ],
568
+ values = 'value1' )
569
+ expected = DataFrame (np .array ([[0 , 3 , 1 , np .nan , 2 , np .nan ],
570
+ [np .nan , np .nan , np .nan , 4 , np .nan , 5 ]]),
571
+ index = ['X' , 'Y' ], columns = exp_col )
572
+ tm .assert_frame_equal (result , expected )
573
+
530
574
531
575
class TestCrosstab (tm .TestCase ):
532
576
0 commit comments