3

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?

mutter123
  • 45
  • 5
  • looks like you want to create a multi-level (multiindex) dataframe. See if this helps [1](https://stackoverflow.com/questions/40820017/how-to-create-a-multilevel-dataframe-in-pandas) or [2](https://stackoverflow.com/questions/61181247/how-do-i-create-a-dataframe-with-multi-level-columns) – Joe Ferndz Nov 17 '20 at 22:00
  • Does this answer your question? [How do I create a DataFrame with multi-level columns?](https://stackoverflow.com/questions/61181247/how-do-i-create-a-dataframe-with-multi-level-columns) – Joe Ferndz Nov 17 '20 at 22:00
  • @JoeFerndz no, unfortunately. These examples have repeating columns under the headers. In my case, the columns are different, and, most importantly, the number of columns under one header is different – mutter123 Nov 17 '20 at 22:06

1 Answers1

2

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']])
sordnay
  • 121
  • 2