CarlosE
CarlosE

Reputation: 960

Pandas DataFrames in Jupyter: formatting index and columns separately

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

Upvotes: 1

Views: 1803

Answers (2)

CarlosE
CarlosE

Reputation: 960

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

Upvotes: 0

HYRY
HYRY

Reputation: 97301

Just add following style:

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

Upvotes: 1

Related Questions