如何使用 pandas 为包含特定字符串的单元格中的文本着色 [英] How to color text in a cell containing a specific string using pandas

查看:34
本文介绍了如何使用 pandas 为包含特定字符串的单元格中的文本着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

After running my algorithms I saved all the data in an excel file using pandas.

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

现在,一些单元格包含包含-->"的字符串.我有这些单元格的行号和列号:

Now, some of the cells contain strings which includes "-->" in it. I have the row and column number for those cells using:

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

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

But I couldn't figure how to color those cells or atleast the whole text in it.

有什么建议/提示吗?

推荐答案

您可以像这样在 Excel 中使用条件格式:

You could use a conditional format in Excel like this:

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 文档中.

See Adding Conditional Formatting to Dataframe output in the XlsxWriter docs.

这篇关于如何使用 pandas 为包含特定字符串的单元格中的文本着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆