python-3.x - 使用 pandas dataframe 和 xlsxwriter 根据单元格值突出显示 Excel 单元格

标签 python-3.x pandas dataframe xlsxwriter

我有一个 csv 文件。完成一定的处理后,必须将其保存为excel文件。

我将其作为 pandas 数据框打开,并在进行一些清理(重命名和重新排列列,删除几列)之后,我必须替换空值,或者如果单元格值为“N/A”到“DN”。目前我为此使用两行代码。

df.replace('', np.nan, inplace = True)
df.replace('N/A', np.nan, inplace = True)
df = df.fillna("DN")

然后,我必须用黄色突出显示值为“DN”的单元格

我正在尝试使用这篇文章中提到的代码 How Do I Highlight Rows Of Data? Python Pandas issue 。但在输出 excel 中,没有任何内容突出显示。下面是我当前正在使用的代码

df.replace('', np.nan, inplace = True)
df.replace('N/A', np.nan, inplace = True)
df = df.fillna("NA")
df.index = np.arange(1, len(df) + 1)

def high_color(val):
    color = 'yellow' if val == 'NA' else ''
    return 'color: {}'.format(color)
result = df.style.applymap(high_color)

writer_orig = pd.ExcelWriter(out_name, engine='xlsxwriter')
df.to_excel(writer_orig, sheet_name='report', index=True, index_label="S_No", freeze_panes=(1,1))

workbook  = writer_orig.book
worksheet = writer_orig.sheets['report']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'fg_color': '#ffcccc',
    'border': 1})
    
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)
writer_orig.close()

任何类型的建议都会非常有帮助。

最佳答案

您必须使用 结果 Styler 导出到 Excel:

# Demo
def high_color(val):
    return 'background-color: yellow' if val == 'NA' else None

result = df.style.applymap(high_color)
result.to_excel('styler1.xlsx')
df.to_excel('styler2.xlsx')

结果导出

enter image description here

df导出

enter image description here

关于python-3.x - 使用 pandas dataframe 和 xlsxwriter 根据单元格值突出显示 Excel 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75221463/

相关文章:

python - Pandas Dataframe 行基于值间隔的平均值

python - 迈克尔·道森的问答游戏作业

python - 类型错误 : method() takes 1 positional argument but 2 were given

python - 如何更改 Raspberry Pi 中的默认 Python 版本

python - 如何减去 Pandas Dataframe 中的两个日期时间值

python - Pandas 在数据框中丢弃单词

python - 自定义 Base64 编码器无法正确编码

python - 如何将一行读入 Pandas——已被返回字符打破

python - 对数据框列进行排序/对齐,以便行字符串值与主列表列匹配,如果列中不匹配则打印 0

dataframe - 如何从记录/行创建数据框