【问题标题】:Stylize cell if word found in Pandas DataFrame?如果在 Pandas DataFrame 中找到单词,则样式化单元格?
【发布时间】:2018-07-24 21:34:20
【问题描述】:

我在网上看到如何格式化Pandas DataFrame with .style

但是,我有一个包含一堆文本的表格,并且希望能够根据里面的单词格式化单元格。借用上述链接参考中的这个逻辑:

def color_negative_red(val):
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

例如,如果单元格中有单词“BBC”,则将单元格涂成红色。如果“XYZ”在单元格中,则将其涂成绿色。如果单元格中有“ZYX”等,则将其涂成黑色。

def style_dataframe(val):
    color = "red" if "BBC" in val else "white" # fuzzy match 'BBC'
    color = "green" if val == "XYZ" else color # find exact match
    color = "black" if val == "ZYX" else color # find exact match
    return 'background-color: %s' % color   
...   
df.style.applymap(style_dataframe)
df.to_html("test.html")

但是,这不会给任何东西上色。

test.html 的截图:

【问题讨论】:

    标签: python pandas pandas-styles


    【解决方案1】:

    你有一个大体的想法,干得好!

    您需要添加的部分实际上是渲染格式。

    在保存html 之前,这样做:

    ...
    stylized_df = df.style.applymap(style_dataframe)
    with open("test.html","w") as html:
        html.write(stylized_df.render())
    

    注意:当您收到错误消息时,您不能执行if "bbc" in val

    TypeError: ("'NoneType' 类型的参数不可迭代", '发生在索引作者处')

    要解决这个问题,请调整 If 语句流:

    def style_dataframe(val):
        color = "white"
        if val is not None:
            if "bbc" in val:
                color = "red"
            if val == "The Wall Street Journal":
                color = "green"
        return 'background-color: %s' % color
    

    【讨论】:

    • @AsheKetchum 而不是 if not None?
    • @Batman 是的,我认为有关于“请求宽恕而不是许可”的想法。我以为它是在 python 的禅宗中,但也许我在其他地方看到了它。也许像stackoverflow.com/a/12265860/7571052 这样的东西?我想在这种情况下并没有太大的区别:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多