Jason S
Jason S

Reputation: 189646

displaying Pandas DataFrame in HTML without the extra row

If I use DataFrame.set_index, I get this result:

import pandas as pd

df = pd.DataFrame([['foo',1,3.0],['bar',2,2.9],
                   ['baz',4,2.85],['quux',3,2.82]],
                 columns=['name','order','gpa'])
df.set_index('name')

enter image description here

Note the unnecessary row... I know it does this because it reserves the upper left cell for the column title, but I don't care about it, and it makes my table look somewhat unprofessional if I use it in a presentation.

If I don't use DataFrame.set_index, the extra row is gone, but I get numeric row indices, which I don't want:

enter image description here

If I use to_html(index=False) then I solve those problems, but the first column isn't bold:

import pandas as pd
from IPython.display import HTML

df = pd.DataFrame([['foo',1,3.0],['bar',2,2.9],
                   ['baz',4,2.85],['quux',3,2.82]],
                 columns=['name','order','gpa'])
HTML(df.to_html(index=False))

enter image description here

If I want to control styling to make the names boldface, I guess I could use the new Styler API via HTML(df.style.do_something_here().render()) but I can't figure out how to achieve the index=False functionality.

What's a hacker to do? (besides construct the HTML myself)

Upvotes: 7

Views: 4261

Answers (2)

Private
Private

Reputation: 2694

These days pandas actually has a keyword for this:

df.to_html(index_names=False)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html

Upvotes: 3

Jason S
Jason S

Reputation: 189646

I poked around in the source for Styler and figured it out; if you set df.index.names = [None] then this suppresses the "extra" row (along with the column header that I don't really care about):

import pandas as pd

df = pd.DataFrame([['foo',1,3.0],['bar',2,2.9],
                   ['baz',4,2.85],['quux',3,2.82]],
                 columns=['name','order','gpa'])
df = df.set_index('name')
df.index.names = [None]
df

enter image description here

Upvotes: 5

Related Questions