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

标签 python excel python-3.x pandas xlrd

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

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

现在,一些单元格包含包含“-->”的字符串。我有这些单元格的行号和列号,使用:
xl_rowcol_to_cell(rows[i],cols[i])

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

有什么建议/提示吗?

最佳答案

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



输出:

enter image description here

Adding Conditional Formatting to Dataframe output在 XlsxWriter 文档中。

关于python - 如何使用 Pandas 为包含特定字符串的单元格中的文本着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57997345/

相关文章:

python - pymssql : Inserting mutliple values into a table

python - 为什么单击一次 ToolButton 上的 pygtk 回调会执行两次

excel - 如何在 Excel-VBA 中将此 ElseIf 编写为 Case 语句?

Excel VBA - 根据值更改单元格颜色

python - 在 Linux 上手动更改声音输出设备

ajax - 当浏览器中的值发生变化时,如何刷新 django 管理表单?

python - 在 Tkinter 中单击后禁用按钮

text - 如果内容总和 = 零并跳过包含任何文本的行,如何隐藏 Excel 行?

python - 为什么我的交换列表的两个元素的代码出错了?

python - 如何让我的 python 应用程序在继续之前等待某个子进程