[英]How to color text in a cell containing a specific string using 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()
输出:
请参阅XlsxWriter文档中的向数据框输出添加条件格式设置 。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.