4

I have a Pandas DataFrame where the index looks similar to this:

"test1 2011"
"test2 2011"
"test3 2011"
"test1 2012"
"test2 2012"
"test3 2012"
...

Is there an easy way to make this into a MultiIndex?

Example of desirable output:

                 columns_of_data
"2011" "test1"   N/A
       "test2"   N/A
       "test3"   N/A
"2012" "test1"   N/A
       "test2"   N/A
       "test3"   N/A
2
  • Can you give an example of the desired outcome? Commented Jan 12, 2014 at 10:45
  • @greole Added example output Commented Jan 12, 2014 at 10:50

1 Answer 1

4

If you have this index:

idx = ["test1 2011",
"test2 2011",
"test3 2011",
"test1 2012",
"test2 2012",
"test3 2012"]

idx = pd.Index(idx)

Then you can split each index value and feed it to MultiIndex.from_tuples (the [::-1] is to reverse the order of 'test1' and '2013', as in your desired output):

midx = pd.MultiIndex.from_tuples([x.split()[::-1] for x in idx])

Eg, this gives such a dataframe:

In [12]: pd.DataFrame(np.random.randn(6,2), index=midx)
Out[12]:
                   0         1
2011 test1  0.340850  2.295460
     test2  1.201304 -0.546234
     test3 -0.667596  1.114521
2012 test1 -0.116098 -0.494520
     test2  0.663173 -0.834933
     test3  0.709935 -0.195774
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.