Jupyter中的Pandas DataFrames:分别格式化索引和列

时间:2016-12-10 21:34:07

标签: python pandas dataframe jupyter display

这是问题"Pandas DataFrames in Jupyter: columns of equal width and centered"的变体。

我们如何显示一个索引数据框,除了索引以外,所有列都居中?而且,我们如何控制索引的宽度和其他属性?

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 个答案:

答案 0 :(得分:1)

只需添加以下样式:

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

答案 1 :(得分: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