Jupyter中的Pandas数据帧:分别格式化索引和列

2024-09-28 22:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这是问题"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


Tags: columnstextpandasdfdatarawwidthcompany
2条回答

只需添加以下样式:

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

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

相关问题 更多 >