使用不同颜色对python数据框列值进行条件格式设置

2024-09-30 10:39:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据df中的一列的值为其着色。我只尝试了一个值,但没有得到任何颜色的结果。这是我的密码

writer = pd.ExcelWriter('resultcolored.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet')
workbook = writer.book
worksheet = writer.sheets["Sheet"]



format = workbook.add_format({'bg_color':   '#C6EFCE',
                               'font_color': '#006100'})
worksheet.conditional_format( 'AJ1:AJ10',
    {   'type': 'text',
        'criteria': 'containing',
        'value': 'Direct',
        'format': format
    }
)
writer.save()

它保存文件,但不删除任何值。你能帮帮我吗


Tags: format密码df颜色xlsxenginesheetcolor
1条回答
网友
1楼 · 发布于 2024-09-30 10:39:03

它应该像预期的那样工作。以下是基于您的代码的工作示例:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': ['Foo', 'Director', 'bar', 'Directory', 'Baz']})

# 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']

format = workbook.add_format({'bg_color':   '#C6EFCE',
                              'font_color': '#006100'})

# Apply a conditional format to the cell range.
worksheet.conditional_format( 'B2:B6',
    {   'type': 'text',
        'criteria': 'containing',
        'value': 'Direct',
        'format': format
    }
)

writer.save()

输出

enter image description here

相关问题 更多 >

    热门问题