我正在处理一个数据框(来自 Excel 文件),我想格式化单元格。
DF 具有以下内容(作为示例):
我想将包含“-->”的单元格涂成红色。有什么建议么?我知道 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)
对于写入 Excel 使用:
df.style.applymap(make_your_style).to_excel(file, engine='openpyxl', index=False)
关于python - 如果Python中的单元格包含特定字符,如何为其着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66420826/