3

Am using Jupyter Notebooks and would like to display a pandas DataFrame applying the same width to all the columns, with all values centered. What's the simplest way to achieve this, without importing libraries?

import pandas as pd
raw_data = {'regiment': ['Nighthawks', 'Dragoons'], 
    'company': ['1st', '2nd'], 
    'name': ['Miller', 'Jacob'], 
    'preTestScore': [4, 24],
    'postTestScore': [25, 94]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])
df

Unaligned columns

CarlosE
  • 858
  • 2
  • 11
  • 22

1 Answers1

10

New in pandas 0.17.1 is the pd.Styler:

raw_data= {'regiment': ['Nighthwawks','Dragons'],
            'company':['1st','2nd'],
            'name':['Miller', 'Ali'],
            'preTestScore':[4,120]}
df = pd.DataFrame(raw_data)

d = dict(selector="th",
    props=[('text-align', 'center')])

df.style.set_properties(**{'width':'10em', 'text-align':'center'})\
        .set_table_styles([d])

enter image description here

Julien Marrec
  • 11,605
  • 4
  • 46
  • 63
  • 1
    I was about to suggest you answer this [possible duplicate](http://stackoverflow.com/questions/18876022/how-to-format-ipython-html-display-of-pandas-dataframe) too, but I see you already did. Upvoted! – IanS Dec 06 '16 at 11:16
  • Thank you @Julien, this is exactly what I needed. PS: I tried to add the code but could not find a way to display the output. This was the first time I use stackoverflow. Suggestions most welcome. – CarlosE Dec 06 '16 at 15:17
  • 2
    Format the output as code as well (indented by 4 spaces). Usually `print(df)` will do the job, just copy and paste that, then select your lines and click on the `{}` or press `CTRL`+`K` – Julien Marrec Dec 06 '16 at 17:00
  • @JulienMarrec is it ok to upload a picture in an answer? – Guzman Ojero Aug 28 '21 at 13:04
  • If it's helpful sure? – Julien Marrec Aug 30 '21 at 10:25