Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiindex based on single index

Tags:

python

pandas

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
like image 796
Jimmy C Avatar asked Oct 19 '25 05:10

Jimmy C


1 Answers

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
like image 56
joris Avatar answered Oct 21 '25 19:10

joris