Pandas setting multi-index on rows, then transposing to columns

sheridp picture sheridp · Aug 16, 2016 · Viewed 16.3k times · Source

If I have a simple dataframe:

print(a)

  one  two three
0   A    1     a
1   A    2     b
2   B    1     c
3   B    2     d
4   C    1     e
5   C    2     f

I can easily create a multi-index on the rows by issuing:

a.set_index(['one', 'two'])

        three
one two      
A   1       a
    2       b
B   1       c
    2       d
C   1       e
    2       f

Is there a similarly easy way to create a multi-index on the columns?

I'd like to end up with:

    one A       B       C   
    two 1   2   1   2   1   2
    0   a   b   c   d   e   f

In this case, it would be pretty simple to create the row multi-index and then transpose it, but in other examples, I'll be wanting to create a multi-index on both the rows and columns.

Answer

piRSquared picture piRSquared · Aug 16, 2016

Yes! It's called transposition.

a.set_index(['one', 'two']).T

enter image description here


Let's borrow from @ragesz's post because they used a much better example to demonstrate with.

df = pd.DataFrame({'a':['foo_0', 'bar_0', 1, 2, 3], 'b':['foo_0', 'bar_1', 11, 12, 13],
    'c':['foo_1', 'bar_0', 21, 22, 23], 'd':['foo_1', 'bar_1', 31, 32, 33]})

df.T.set_index([0, 1]).T

enter image description here