如何使用 pandas 为包含特定字符串的单元格中的文本着色

Abh*_*Pai 1 python excel xlrd python-3.x pandas

运行算法后,我使用 pandas 将所有数据保存在 Excel 文件中。

writer = pd.ExcelWriter('Diff.xlsx', engine='xlsxwriter')
Run Code Online (Sandbox Code Playgroud)

现在,某些单元格包含其中包含“-->”的字符串。我使用以下方法获得这些单元格的行号和列号:

xl_rowcol_to_cell(rows[i],cols[i])
Run Code Online (Sandbox Code Playgroud)

但我不知道如何为这些单元格或至少其中的整个文本着色。

有什么建议/提示吗?

jmc*_*ara 5

您可以在 Excel 中使用条件格式,如下所示:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': ['foo', 'a --> b', 'bar']})

# 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.
df.to_excel(writer, sheet_name='Sheet1')

# 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'})

# Apply a conditional format to the cell range.
worksheet.conditional_format(1, 1, len(df), 1,
                             {'type':     'text',
                              'criteria': 'containing',
                              'value':    '-->',
                              'format':   format1}) 

# Close the Pandas Excel writer and output the Excel file.
writer.save()


Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

请参阅XlsxWriter 文档中的向数据帧输出添加条件格式。