Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping/Ordering multi-index columns in pandas

Following the documentation code on multi-indexing, I do the following:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'],
          ['one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

df2 = pd.DataFrame(np.random.randn(3, 6), index=['A', 'B', 'C'], columns=index)

This yields a dataframe that looks like:

first        bar                 baz                 foo
second       one       two       one       two       one       two
A      -0.398965 -1.103247 -0.530605  0.758178  1.462003  2.175783
B      -0.356856  0.839281  0.429112 -0.217230 -2.409163 -0.725177
C      -2.114794  2.035790  0.059812 -2.197898 -0.975623 -1.246470

My problem is that in my output (to an HTML table), I would like to group based on the second level index, rather than the first. Yielding something that looks like:

second       one                           two
first        bar       baz       foo       bar       baz       foo
A      -0.398965 -0.530605  1.462003 -1.103247  0.758178  2.175783
B      -0.356856  0.429112 -2.409163  0.839281 -0.217230 -0.725177
C      -2.114794  0.059812 -0.975623  2.035790 -2.197898 -1.246470

Is there an easy way to swap and re-group my column indices?

like image 780
MarkD Avatar asked Nov 03 '16 21:11

MarkD


1 Answers

swaplevel with sort_index

df2.swaplevel(0, 1, 1).sort_index(1)

enter image description here

like image 52
piRSquared Avatar answered Oct 13 '22 00:10

piRSquared