【发布时间】: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")
但是,这不会给任何东西上色。
【问题讨论】:
标签: python pandas pandas-styles