【问题标题】:display DataFrame() values in bold font in one row only仅在一行中以粗体显示 DataFrame() 值
【发布时间】:2019-01-27 00:37:37
【问题描述】:

有数据框 summary 直接从 jupyter 单元调用

summary #(Shift + Enter)

如何使突出显示的行(最后一行)以粗体显示?

【问题讨论】:

    标签: pandas ipython jupyter-notebook


    【解决方案1】:

    请提供代码以至少生成您发布的数据框。

    对于你想要的,你可以使用 style.applymap() 函数。剩下的就是找到可以设置为粗体的字体的正确属性以及如何设置最后一行的索引。

    import pandas as pd
    
    def df_style(val):
        return "font-weight: bold"
    
    summary = pd.DataFrame([[0, 0, 0, 0, 0], [1620, 203, 392, 651, 2236]],
                           index=["None", "Total"])
    
    # get a handle on the row that starts with `"Total"`, i.e., the last row here
    last_row = pd.IndexSlice[summary.index[summary.index == "Total"], :])
    # and apply styling to it via the `subset` arg; first arg is styler function above
    summary.style.applymap(df_style, subset=last_row)
    
    print(summary)
    

    下面是输出:

    【讨论】:

    • @B.Malysz 我的意思是发布代码以生成您在图片中发布的数据框。而不是让其他人进行反向工程。我认为这不是机密。
    • 此代码不适用于我的情况。我也想问一下,df_style函数在哪里使用?
    • @DionisiusPratama 确实是错误的,现在已修复;函数用作style.applymap 的第一个参数。
    【解决方案2】:

    试试这个:

    def highlight_max(x):
        return ['font-weight: bold' if v == x.loc[4] else ''
                    for v in x]
    df = pd.DataFrame(np.random.randn(5, 2))
    df.style.apply(highlight_max)
    

    【讨论】:

    • 我收到了这个错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().你知道如何解决它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2016-05-25
    相关资源
    最近更新 更多