我有一个 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')
从结果
导出
从df
导出
关于python-3.x - 使用 pandas dataframe 和 xlsxwriter 根据单元格值突出显示 Excel 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75221463/