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

How to color text in a cell containing a specific string using pandas

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

writer = pd.ExcelWriter('Diff.xlsx', engine='xlsxwriter')

现在,一些单元格包含包含“-->”的字符串。我使用这些单元格的行号和列号:

xl_rowcol_to_cell(rows[i],cols[i])

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

任何suggestions/tips?

def highlight (dataframe):

    if  dataframe[dataframe['c'].str.contains("-->")]:

        return ['background-color: yellow']*5
    else:
        return ['background-color: white']*5


df.style.apply(highlight, axis=1)

您可以像这样在 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()


输出:

请参阅 XlsxWriter 文档中的 Adding Conditional Formatting to Dataframe output