1

This is a variation of the question "Pandas DataFrames in Jupyter: columns of equal width and centered".

How can we display an indexed dataframe with all columns centered except the index, which should be aligned left? And also, how can we control the width and other attributes of the index?

import pandas as pd
raw_data = {'Regiment': ['Nighthawks', 'Raptors'], 
    'Company': ['1st', '2nd'], 
    'preTestScore': [4, 24],
    'postTestScore': [25, 94]}
df = pd.DataFrame(raw_data, columns = ['Regiment', 'Company', 'preTestScore', 'postTestScore']).set_index('Regiment')
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

2 Answers 2

1

Just add following style:

style_index = dict(selector=".row_heading", props=[("text-align", "right")])

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

1 Comment

Thank you. I was not aware you can have more than one styles dict in set_table_styles.
0
import pandas as pd
raw_data = {'Regiment': ['Nighthawks', 'Raptors'], 
    'Company': ['1st', '2nd'], 
    'preTestScore': [4, 24],
    'postTestScore': [25, 94]}
df = pd.DataFrame(raw_data, columns = ['Regiment', 'Company', 'preTestScore', 'postTestScore']).set_index('Regiment')
d1 = dict(selector="th", props=[('text-align', 'center')] )
d2 = dict(selector=".row_heading", props=[("text-align", "left")])

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

Solution

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.