使用 pandas dataframe 和 xlsxwriter 根据单元格值突出显示 Excel 单元格

问题描述 投票:0回答:2

我有一个 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”的单元格

我正在尝试使用本文中提到的代码如何突出显示数据行? Python Pandas 问题。但在输出 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()

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

python-3.x pandas excel dataframe xlsxwriter
2个回答
2
投票

您无法使用 pandas.ExcelWriter

Styler 对象
保存到 Excel 电子表格。

类 pandas.ExcelWriter(路径, 引擎=无, date_format=无, datetime_format=无,mode='w',storage_options=无, if_sheet_exists=无,engine_kwargs=无,**kwargs)
用于将 DataFrame 对象写入 Excel 工作表的类。

您需要使用 xlsxwriter

 中的 
worksheet.conditional_format 来突出显示每个单元格中的值。此外,您可以将
na_values
作为 kwarg 传递给
pandas.read_csv
,以自动将值列表视为
NaN

from xlsxwriter.utility import xl_rowcol_to_cell

df = pd.read_csv('/tmp/inputfile.csv', na_values=['', 'N/A']).fillna('DN')

l = df.columns.get_indexer(df.columns).tolist()
xshape = list(map(xl_col_to_name, [e+1 for e in l])) 
max_row, max_col = df.shape

with pd.ExcelWriter("/tmp/outputfile.xlsx") as writer:
    df.to_excel(writer, sheet_name='report', index=True,
                index_label='S_No', freeze_panes=(1,1))
    
    wb = writer.book
    ws = writer.sheets['report']
    
    format_header = wb.add_format({'bold': True, 'fg_color': '#ffcccc', 'border': 1})
    for idx, col in enumerate(['S_No'] + list(df.columns)):
        ws.write(0, idx, col, format_header)  
        
    format_dn = wb.add_format({'bg_color':'yellow', 'font_color': 'black'})
    ws.conditional_format(f'{xshape[0]}2:{xshape[-1]}{str(max_row+1)}',
                                 {'type': 'cell', 'criteria': '==',
                                  'value': '"DN"', 'format': format_dn})

输出:


1
投票

您必须使用

result
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')

result

导出

df

导出

© www.soinside.com 2019 - 2024. All rights reserved.