[英]Highlight blank cell, where cell in adjacent column is not empty
Wondering if anyone can help.想知道是否有人可以提供帮助。 I have an (unfortunately private) DataFrame which my program exports to excel.
我有一个(不幸的是私人)DataFrame,我的程序导出到 excel。
I would like to be able to highlight red any blank cells in column 1, where the cell in column 2 is not blank.我希望能够将第 1 列中的任何空白单元格突出显示为红色,其中第 2 列中的单元格不是空白的。
For example - if the data looked like this, I'd want to produce an excel file where 0,col1 and 2,col1 are highlighted red.例如 - 如果数据看起来像这样,我想生成一个 excel 文件,其中 0,col1 和 2,col1 以红色突出显示。
col1 ![]() |
col2 ![]() |
---|---|
0.5 ![]() |
|
1 ![]() |
1.0 ![]() |
2.0 ![]() |
|
3 ![]() |
3.0 ![]() |
One way to do it is to use conditional formatting in the Excel to highlight the cells.一种方法是在 Excel 中使用条件格式来突出显示单元格。 Something like this:
像这样的东西:
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Col 1': [1, '', '', '', 5],
'Col 2': [1, 2, '', 4, 5]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
# Note, the index column is omitted in this example.
df.to_excel(writer, sheet_name='Sheet1', index=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape
# Apply a conditional format to the required cell range.
worksheet.conditional_format(1, 0, max_row, 0,
{'type': 'formula',
'criteria': '=AND(ISBLANK($A2), NOT(ISBLANK($B2)))',
'format': format1})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Output : Output :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.