python - 如何在python中有条件地为输出的excel的单元格着色?
问题描述
我必须以这种方式为我的 xls 输出的单元格(仅用于确定的列)着色:
green positive value
gray NaN value
red negative valute
假设我的数据框:
df
a b c d e
0 2 8 -8 3 -4
1 -4 2 9 0 NaN
2 1 0 NaN 8 0
3 5 1 7 1 3
4 6 0 -2 4 -2
第 ti 列着色:a、c 和 e。
我的实际代码很简单:
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer,'Sheet1', index=False)
writer.save()
解决方案
您可以创建一个函数来突出显示...
def color_cells():
# put your condition here
return ['background-color: yellow']
然后应用你的突出显示
df.style.apply(color_cells)
查看此文档以获取更多信息
例如,您可以突出显示最大值:
def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
您可以定义自己的条件
推荐阅读
- java - 在 SSL 中使用 Spring BOOT 进行 SOAP 身份验证
- pine-script - tradingview pine 脚本中的 if 语句问题
- matlab - 使用 fmincon() 求解一个特殊的非线性程序
- get - 如何从 FTP 中获取具有特定名称的文件夹和子文件夹
- typescript - 如何理解类型 any、unknown、{} 之间以及它们与其他类型之间的关系?
- php - 在 laravel 中为未登录用户授权资源
- django - 特定 URL 调用
- python-sphinx - 如何在 Sphinx 中确保正确的智能报价?
- php - PHP / MySQL:来自 MySQL 的数据不显示在选择选项中(下拉列表)
- azure - 防止 Azure Live Metrics Stream 将每次轮询记录到队列中