【问题标题】:Pandas DataFrames in Jupyter: formatting index and columns separatelyJupyter 中的 Pandas DataFrames:分别格式化索引和列
【发布时间】:2016-12-10 21:34:07
【问题描述】:

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

【问题讨论】:

    标签: python pandas dataframe jupyter display


    【解决方案1】:

    只需添加以下样式:

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

    【讨论】:

    • 谢谢。我不知道你可以在 set_table_styles 中拥有多个样式字典。
    【解决方案2】:
    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])
    

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      相关资源
      最近更新 更多