7

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)

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Not really sure what this does, however. :/
thank you, this is useful in general. It simply removes the index name... (I noticed the extra row sometimes in outputs, and was also puzzled what it means.)
3

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

Comments

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.