mutter123
mutter123

Reputation: 45

How to merge cells in pandas dataframe to use as headers?

I'm making a very simple single row dataframe in pandas:

df = pd.DataFrame([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]],
                  columns=['x', 'y',
                           'Vx', 'Vy', 'V',
                           'ax', 'ay', 'a',
                           'at', 'an', 'r'])

and it looks like this

+----+----+----+----+----+----+----+----+----+----+----+
|  x |  y |  Vx|  Vy|  V |  ax|  ay|  a |  at|  an|  r |
+----+----+----+----+----+----+----+----+----+----+----+
|  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |  9 | 10 | 11 |
+----+----+----+----+----+----+----+----+----+----+----+

but I want it to look like this:

+----+----+----+----+----+----+----+----+----+----+----+
|coordin. |     speed    |       acceleration     |rad |
+----+----+----+----+----+----+----+----+----+----+----+
|  x |  y |  Vx|  Vy|  V |  ax|  ay|  a |  at|  an|  r |
+----+----+----+----+----+----+----+----+----+----+----+
|  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |  9 | 10 | 11 |
+----+----+----+----+----+----+----+----+----+----+----+

So I want to use merged cells as headers of some sort. The tricky thing is that as you can see each header covers different number of columns. What should I do to make my table look like this?

Upvotes: 3

Views: 2632

Answers (1)

sordnay
sordnay

Reputation: 121

Seems that you want a multiindex on the columns...

df2 = pd.DataFrame([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]],
                  columns=[['coord','coord',
                  'vel','vel','vel',
                  'acc','acc','acc','acc','acc',
                  'rad'],
                  ['x', 'y',
                  'Vx', 'Vy', 'V',
                  'ax', 'ay', 'a',
                  'at', 'an', 'r']])

Upvotes: 2

Related Questions