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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With