1

I have the following dataframe:

import pandas as pd

df = pd.DataFrame({'text': ['foo foo', 'bar bar'],
                 'number': [1, 2]})
df

dataframe

How do I center-align both the column titles/headers and the values in a dataframe, and how do I drop the index (the column with the values 0 and 1) in a dataframe?

Oleg
  • 538
  • 8
  • 16
Leockl
  • 1,412
  • 2
  • 12
  • 29
  • 1
    In order to drop the index you have to set a different index, unless you want to print it or save to a file, then you can set the relevant argument to `False` Regarding the alignment, where are you trying to align it? – Oleg Apr 22 '20 at 07:13
  • Hi @Oleg, I am wanting to align the headers and values to be in the center within each of it's respective "box" – Leockl Apr 22 '20 at 07:33
  • I found this `df.style.set_properties(**{'text-align': 'center'})` which would center-align the values, but how do I center-align the headers as well? – Leockl Apr 22 '20 at 07:39
  • 1
    It sounds that what you want is to edit the alignment settings of the notebook you're using When you're writing `df` it's similar to writing `display(df)` as it's mentioned here https://stackoverflow.com/a/29665452/8219391 Also you should check out pandas documentation on this: https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Table-styles – Oleg Apr 22 '20 at 07:42
  • 1
    Ok many thanks @Oleg. I actually found an answer to this and have posted it below. – Leockl Apr 22 '20 at 08:15

3 Answers3

2

Found an answer for this. This should do the trick to center-align both headers and values and hiding the index:

df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
df1.set_properties(**{'text-align': 'center'}).hide_index()
Leockl
  • 1,412
  • 2
  • 12
  • 29
  • This works but the result is not a dataframe and Im not sure what it is (Styler?). How do we do the same thing but output a dataframe? – big_soapy Jan 22 '21 at 21:41
1

Try IPython.display

from IPython.display import HTML
HTML(df.to_html(index=False))

enter image description here

Sujit Dhamale
  • 1,103
  • 9
  • 13
  • Thanks @Sujit Dhamale. What about center-aligning the headers and values to be in the center within each of it's respective "box" in the dataframe? – Leockl Apr 22 '20 at 07:34
  • 2
    I found this `df.style.set_properties(**{'text-align': 'center'})` which would center-align the values, but how do I center-align the headers as well? – Leockl Apr 22 '20 at 07:39
-1
df.style.set_properties(subset=["Feature", "Value"], **{'text-align': 'center'})