[英]How to color the cells of an excel of output conditionally in python?
I have to color cell of my xls output (only for determinate columns) in this way: 我必须以这种方式为我的xls输出的单元格着色(仅用于确定的列):
green positive value
gray NaN value
red negative valute
Suppese my data frame: 提供我的数据框:
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
column ti colorate: a, c and e. ti列:a,c和e。
My actually code is simply: 我的实际代码很简单:
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer,'Sheet1', index=False)
writer.save()
You can create a function to do the highlighting... 您可以创建一个函数来突出显示...
def color_cells():
# put your condition here
return ['background-color: yellow']
And then apply your highlighting 然后应用突出显示
df.style.apply(color_cells)
Look at this document for more information 查看此文档以获取更多信息
For example you can highlight max value : 例如,您可以突出显示最大值:
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]
You can define your own condition 您可以定义自己的条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.