@@ -617,6 +617,72 @@ def test_insert(self):
617
617
result = period_range ("2017Q1" , periods = 4 , freq = "Q" ).insert (1 , na )
618
618
tm .assert_index_equal (result , expected )
619
619
620
+ def test_contains_raise_error_if_period_index_is_in_multi_index (self ):
621
+ # issue 20684
622
+ df = DataFrame (
623
+ {
624
+ "A" : [Period ("2019" ), "x1" ],
625
+ "B" : ["y1" , Period ("2018" )],
626
+ "C" : ["z1" , "z2" ],
627
+ "V1" : [1 , 2 ],
628
+ "V2" : [10 , 20 ],
629
+ }
630
+ ).set_index (["A" , "B" , "C" ])
631
+ msg = r"Period\('2019', 'A-DEC'\), 'foo', 'bar'"
632
+ with pytest .raises (KeyError , match = msg ):
633
+ df .loc [(Period ("2019" ), "foo" , "bar" )]
634
+
635
+ msg = r"'foo', Period\('2018', 'A-DEC'\), 'bar'"
636
+ with pytest .raises (KeyError , match = msg ):
637
+ df .loc [("foo" , Period ("2018" ), "bar" )]
638
+
639
+ pbc = DataFrame (
640
+ {"p" : [Period ("2017" )], "b" : ["b1" ], "c" : ["c1" ], "v" : [1 ]}
641
+ ).set_index (["p" , "b" , "c" ])
642
+ msg = r"Period\('2017', 'A-DEC'\), 'wibble', 'c1'"
643
+ with pytest .raises (KeyError , match = msg ):
644
+ pbc .loc [(Period ("2017" ), "wibble" , "c1" )]
645
+
646
+ msg = r"Period\('2017', 'A-DEC'\), 'b1', 'wobble'"
647
+ with pytest .raises (KeyError , match = msg ):
648
+ pbc .loc [(Period ("2017" ), "b1" , "wobble" ), "v" ]
649
+
650
+ ybc = DataFrame ({"y" : ["2017" ], "b" : ["b1" ], "c" : ["c1" ], "v" : [1 ]}).set_index (
651
+ ["y" , "b" , "c" ]
652
+ )
653
+ assert ybc .loc [("2017" , "b1" , "c1" ), "v" ] == 1
654
+
655
+ msg = r"'2017', 'b1', 'wobble'"
656
+ with pytest .raises (KeyError , match = msg ):
657
+ ybc .loc [("2017" , "b1" , "wobble" ), "v" ]
658
+
659
+ pb = DataFrame ({"p" : [Period ("2017" )], "b" : ["b1" ], "v" : [1 ]}).set_index (
660
+ ["p" , "b" ]
661
+ )
662
+ assert pb .loc [(Period ("2017" ), "b1" ), "v" ] == 1
663
+
664
+ msg = r"Period\('2017', 'A-DEC'\), 'wibble'"
665
+ with pytest .raises (KeyError , match = msg ):
666
+ pb .loc [(Period ("2017" ), "wibble" ), "v" ]
667
+
668
+ bcp = pd .DataFrame (
669
+ {"p" : [Period ("2017" )], "b" : ["b1" ], "c" : ["c1" ], "v" : [1 ]}
670
+ ).set_index (["b" , "c" , "p" ])
671
+ assert bcp .loc [("b1" , "c1" , Period ("2017" )), "v" ] == 1
672
+
673
+ msg = r"'b1', 'wibble', Period\('2017', 'A-DEC'\)"
674
+ with pytest .raises (KeyError , match = msg ):
675
+ bcp .loc [("b1" , "wibble" , Period ("2017" )), "v" ]
676
+
677
+ bpc = pd .DataFrame (
678
+ {"p" : [Period ("2017" )], "b" : ["b1" ], "c" : ["c1" ], "v" : [1 ]}
679
+ ).set_index (["b" , "p" , "c" ])
680
+ assert bpc .loc [("b1" , Period ("2017" ), "c1" ), "v" ] == 1
681
+
682
+ msg = r"'b1', Period\('2017', 'A-DEC'\), 'wibble'"
683
+ with pytest .raises (KeyError , match = msg ):
684
+ bpc .loc [("b1" , Period ("2017" ), "wibble" ), "v" ]
685
+
620
686
621
687
def test_maybe_convert_timedelta ():
622
688
pi = PeriodIndex (["2000" , "2001" ], freq = "D" )
0 commit comments