2

I have the following dataframe:

 ID     mutex add  atomic add  cas add  ys_add  blocking ticket  queued fifo
Cores                                                                      
1           21.0         7.1     12.1     9.8             32.2         44.6
2          121.8        40.0    119.2   928.7           7329.9       7460.1
3          160.5        81.5    227.9  1640.9          14371.8      11802.1
4          188.9       115.7    347.6  1945.1          29130.5      15660.1 

There is both a column index (ID) and a row index (Cores). When I use DataFrame.to_html(), I get a table like this:

Actual

Instead, I'd like a table with a single header row, composed of all the column names (but without the column index name ID) and with the row index name Cores in that same header row, like so:

Desired

I'm open to manipulating the dataframe prior to the to_html() call, or adding parameters to the to_html() call, but not messing around with the generated html.

9
  • You could use df.drop([0], axis=0)and then use df.rename{ 'ID' : 'Cores'} Commented Apr 22, 2020 at 19:17
  • df.rename_axis(columns=None ) Commented Apr 22, 2020 at 19:29
  • @QuangHoang - I had already tried this. It doesn't change the output except that ID disapears: the Cores cell still appears in a separate header row from all the column header, like this. Commented Apr 22, 2020 at 19:36
  • did you reassign, i.e. df = df.rename_axis(columns=None)? Commented Apr 22, 2020 at 19:38
  • @QuangHoang, yes, I did. This simply removes the index name, but Cores and the list of column names are still different things entire and even the dataframe text output reflects (it still has cores on a different line from the column headers). Commented Apr 22, 2020 at 19:41

1 Answer 1

5

Initial setup:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],
                 columns = ['attr_a', 'attr_b', 'attr_c', 'attr_c'])

df.columns.name = 'ID'
df.index.name = 'Cores'
df

ID  attr_a  attr_b  attr_c  attr_c
Cores               
0        1       2       3       4
1        5       6       7       8
2        9      10      11      12
3       13      14      15      16

Then set columns.name to 'Cores', and index.name to None. df.to_html() should then give you the output you want.

df.columns.name='Cores'
df.index.name = None
df.to_html()


Cores   attr_a  attr_b  attr_c  attr_c
0            1       2       3       4
1            5       6       7       8
2            9      10      11      12
3           13      14      15      16
Sign up to request clarification or add additional context in comments.

1 Comment

How to do if index has multiple columns

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.