2
votes

For simple table such as the following:

df = pd.DataFrame([[1,2,3],[4,5,6]], index=['a','b'])

   0  1  2
a  1  2  3
b  4  5  6

we can swap two rows 'a' and 'b' by calling:

df.loc[['b','a'],:]
Out[21]: 
   0  1  2
b  4  5  6
a  1  2  3

I expected the loc() call takes the same effect for the following multi-level index table:

df = pd.DataFrame(np.arange(12).reshape((4, 3)),
    index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
    columns=[['Ohio', 'Ohio', 'Colorado'],
    ['Green', 'Red', 'Green']])

     Ohio     Colorado
    Green Red    Green
a 1     0   1        2
  2     3   4        5
b 1     6   7        8
  2     9  10       11

but when I run:

df.loc[['b','a'],:]

The table remains the same.

I could swap the rows by calling the following though:

df.reindex(index=['b', 'a'], level=0)

     Ohio     Colorado
    Green Red    Green
b 1     6   7        8
  2     9  10       11
a 1     0   1        2
  2     3   4        5

What has happened to my df.loc[['b','a'],:]?