【问题标题】:Multi-index pandas pivot table change the font weight from 'bold' to 'normal'多索引熊猫数据透视表将字体粗细从“粗体”更改为“正常”
【发布时间】:2019-10-29 22:15:58
【问题描述】:

pivot table I have

df=pd.DataFrame({'Fruit':['Apple', 'Orange', 'Apple', 'Apple', 'Orange', 'Orange'],
            'Variety':['Fuji', 'Navel', 'Honeycrisp', 'Gala', 'Tangerine', 'Clementine'],
            'Count':[2, 5, 5, 1, 8, 4]})
df_pvt=pd.pivot_table(df, index=['Fruit','Variety'], values=['Count'], aggfunc=np.sum)
df=pd.concat([d.append(d.sum().rename((k, 'SubTotal'))) for k, d in df_pvt.groupby(level=0)]).append(df_pvt.sum().rename(('','GrandTotal')))

pivot table I want

我如何获得“SubTotal”、“GrandTotal”和那些值“粗体”以及 Variety 和 Count 下的其余字体作为“正常”font_weight,就​​像我拥有的​​图像一样?或者任何其他方式,我可以让小计和总计弹出然后数据框的其余部分。

【问题讨论】:

标签: pandas pivot-table


【解决方案1】:

棘手的问题...您需要找到一种方法来选择某些标签。

让我们尝试一下这个用于 Jupyter 笔记本的 CSS 选择器编码。

def styleme(x):
    fw = 'bold' if 'Total' in x.name[1] else 'normal'
    l = [f'font-weight: {fw}']*len(x)
    return l

total_idx = np.where(~df.index.get_level_values(1).str.contains('Total'))

table_style = [{'selector':f'tbody tr th[id*=level1_row{i}]', 'props':[('font-weight','normal')]} for i in total_idx[0]]
df.style.apply(styleme, axis=1).set_table_styles(table_style)

输出:

但是,和以前一样,在上一篇文章中,这种格式并没有延续到 to_excel 输出中的 excel:

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 2019-04-08
    • 1970-01-01
    • 2017-01-20
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多