如何将颜色名称与其十六进制映射以进行条件格式

问题描述 投票:0回答:2

我有下面的数据框:

import pandas as pd

df = pd.DataFrame({'ID': ['ID001', 'ID002', 'ID003', 'ID004', 'ID005', 'ID006'],
                   'Color': ['Red', 'Green', 'Blue', 'Green', 'Yellow', 'Purple']})

      ID   Color
0  ID001     Red
1  ID002   Green
2  ID003    Blue
3  ID004   Green
4  ID005  Yellow
5  ID006  Purple

我正在尝试获得这种 Excel 电子表格输出:

通过使用

xlsxwriter
,我编写的下面的代码没有效果:

with pd.ExcelWriter('TestColor_SpreadSheet.xlsx') as writer:
    df.to_excel(writer, index=False, sheet_name='TestWorksheet')

    workbook = writer.book
    worksheet = writer.sheets['TestWorksheet']

    format_red = workbook.add_format({'bg_color':'#FF0000'})

    worksheet.conditional_format('B1:B7', {'type': 'cell',
                                        'criteria': '=',
                                        'value': "Red",
                                        'format': format_red})

您对如何在

xlsxwriter
甚至使用 pandas 进行此条件格式有任何建议吗?

python excel pandas openpyxl xlsxwriter
2个回答
2
投票

Matplotlib 可以为您将颜色名称转换为 RGB 和十六进制值

>>> from matplotlib import colors
>>> 
>>> colors.to_rgb('blue')
(0.0, 0.0, 1.0)
>>> 
>>> colors.to_hex('blue')
'#0000ff'

1
投票

感谢@jprebys的回答上面和@Sergey的这里,我最终得到了这个代码:

import pandas as pd
from matplotlib import colors

df = pd.DataFrame({'ID': ['ID001', 'ID002', 'ID003', 'ID004', 'ID005', 'ID006'],
                   'Color': ['Red', 'Green', 'Blue', 'Green', 'Yellow', 'Purple']})

# ---- Retrieving HEXes with matplotlib

def to_hex(df):
    return colors.to_hex(df["Color"])

df["HEX"] = df.apply(to_hex, axis=1)

# ---- Creating a dictionary of color names and their HEX

df_colors  = df.loc[:, ["Color", "HEX"]].drop_duplicates()
dico_colors = dict(zip(df_colors["Color"], df_colors["HEX"]))

df.drop(columns="HEX", inplace=True)

# --- Formatting the Excel Spreadsheet

with pd.ExcelWriter('TestColor_SpreadSheet.xlsx') as writer:
    df.to_excel(writer, index=False, sheet_name='TestWorksheet')
    
    workbook = writer.book
    worksheet = writer.sheets['TestWorksheet']
    
    dico_format = {}
    for idx, row in df.iterrows():
        key = row['Color']
        dico_format['bg_color'] = dico_colors[key]
        cell_format = workbook.add_format(dico_format)
        worksheet.write(idx+1, 1, key, cell_format)

注意

'bg_color'
代表背景颜色,根据官方文档

# 输出(Excel 中):

© www.soinside.com 2019 - 2024. All rights reserved.