python - 如果Python中的单元格包含特定字符,如何为其着色?

标签 python pandas styling conditional-formatting

我正在处理一个数据框(来自 Excel 文件),我想格式化单元格。

DF 具有以下内容(作为示例):

<表类=“s-表”> <标题> a b c <正文> 234 --> 500 200 --> 500 0 234 --> 500 400 6 66 34 1

我想将包含“-->”的单元格涂成红色。有什么建议么?我知道 Pandas 有样式功能,但我找不到任何可以帮助我解决问题的东西。

最佳答案

您可以修改color_negative_red用于测试 in 中是否存在子字符串的函数:

def make_your_style(val):
    """
    Takes a scalar and returns a string with
    the css property `'background-color: red'` for string with -->
    """
    color = 'red' if '-->' in str(val) else ''
    return f'background-color: {color}'

df.style.applymap(make_your_style)

img

对于写入 Excel 使用:

df.style.applymap(make_your_style).to_excel(file, engine='openpyxl', index=False)

关于python - 如果Python中的单元格包含特定字符,如何为其着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66420826/

相关文章:

Python 请求响应解码

python - AttributeError : 'GridSearchCV' object has no attribute 'best_params_'

python - 是否有相当于 to_markdown 的功能来读取数据?

python - 在 python 中滚动前 3 个月的唯一总和

html - Bootstrap 列比例

styling - 将 OOTB 样式应用于扩展组件

python - 使用 Docker 创建缓慢的 django 模型实例

python - 如何模拟 `s3fs.FileSystem().glob` ?

python - Pandas TimeGrouper : . median() 的行为与 .quantile(0.5) 不同

html - 如何将光标设置为文本区域的底部,并且文本会随着用户输入而上升?