@@ -2471,3 +2471,48 @@ def test_sort_ascending_list(self):
2471
2471
result = s .sort_index (level = ["third" , "first" ], ascending = [False , True ])
2472
2472
expected = s .iloc [[0 , 4 , 1 , 5 , 2 , 6 , 3 , 7 ]]
2473
2473
tm .assert_series_equal (result , expected )
2474
+
2475
+ def test_multiindex_loc_order (self ):
2476
+ # GH 22797
2477
+ # Try to respect order of keys given for MultiIndex.loc
2478
+ df = pd .DataFrame (
2479
+ np .arange (12 ).reshape ((4 , 3 )),
2480
+ index = [["a" , "a" , "b" , "b" ], [1 , 2 , 1 , 2 ]],
2481
+ columns = [["Ohio" , "Ohio" , "Colorado" ], ["Green" , "Red" , "Green" ]],
2482
+ )
2483
+
2484
+ res = df .loc [["b" , "a" ], :]
2485
+ exp_index = pd .MultiIndex .from_arrays ([["b" , "b" , "a" , "a" ], [1 , 2 , 1 , 2 ]])
2486
+ tm .assert_index_equal (res .index , exp_index )
2487
+
2488
+ res = df .loc [["a" , "b" ], :]
2489
+ exp_index = pd .MultiIndex .from_arrays ([["a" , "a" , "b" , "b" ], [1 , 2 , 1 , 2 ]])
2490
+ tm .assert_index_equal (res .index , exp_index )
2491
+
2492
+ res = df .loc [(["a" , "b" ], [1 , 2 ]), :]
2493
+ exp_index = pd .MultiIndex .from_arrays ([["a" , "a" , "b" , "b" ], [1 , 2 , 1 , 2 ]])
2494
+ tm .assert_index_equal (res .index , exp_index )
2495
+
2496
+ res = df .loc [(["a" , "b" ], [2 , 1 ]), :]
2497
+ exp_index = pd .MultiIndex .from_arrays ([["a" , "a" , "b" , "b" ], [2 , 1 , 2 , 1 ]])
2498
+ tm .assert_index_equal (res .index , exp_index )
2499
+
2500
+ res = df .loc [(["b" , "a" ], [2 , 1 ]), :]
2501
+ exp_index = pd .MultiIndex .from_arrays ([["b" , "b" , "a" , "a" ], [2 , 1 , 2 , 1 ]])
2502
+ tm .assert_index_equal (res .index , exp_index )
2503
+
2504
+ res = df .loc [(["b" , "a" ], [1 , 2 ]), :]
2505
+ exp_index = pd .MultiIndex .from_arrays ([["b" , "b" , "a" , "a" ], [1 , 2 , 1 , 2 ]])
2506
+ tm .assert_index_equal (res .index , exp_index )
2507
+
2508
+ res = df .loc [:, ["Colorado" , "Ohio" ]]
2509
+ exp_columns = pd .MultiIndex .from_arrays (
2510
+ [["Colorado" , "Ohio" , "Ohio" ], ["Green" , "Green" , "Red" ]]
2511
+ )
2512
+ tm .assert_index_equal (res .columns , exp_columns )
2513
+
2514
+ res = df .loc [:, (["Colorado" , "Ohio" ], ["Red" , "Green" ])]
2515
+ exp_columns = pd .MultiIndex .from_arrays (
2516
+ [["Colorado" , "Ohio" , "Ohio" ], ["Green" , "Red" , "Green" ]]
2517
+ )
2518
+ tm .assert_index_equal (res .columns , exp_columns )
0 commit comments