简体   繁体   English

如何在python中有条件地为excel输出的单元格着色?

[英]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.

相关问题 如何用pandas改变excel单元格的颜色(python) - How to change color of excel cells with pandas (python) excel python 中的颜色特定单元格 - color specific cells in excel python 无法通过 Pandas DataFrame 有条件地设置 Excel 单元格的背景颜色 - Unable to set background color of Excel cells conditionally via Pandas DataFrame 如何使用python在excel中合并相同字体颜色的文本单元格? - How to merge same font color text cells in an excel using python? for循环在python中为Excel中的多个单元格着色 - for loop in python to color multiple cells in excel python如何复制excel单元格值及其颜色和方程式等 - How can python copy excel cells value together with its color and equation,etc 如何使用openpyxl和python3为excel工作表中的一系列单元格(列和行)提供字体颜色? - How to give font color to a range of cells (columns and rows) in excel worksheet using openpyxl and python3? 有条件地更改特定单元格的背景颜色 - Conditionally change background color of specific cells 通过pandas-python为excel中的特定单元格添加颜色 - add color to certian cells in excel via pandas - python 如何根据 Python pandas DataFrame 中的单元格的值对不同的单元格进行着色 - How to color different cells based on the value of the cells in a Python pandas DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM