将渐变色数据框导出为Excel

0 投票
1 回答
67 浏览
提问于 2025-04-12 07:22

我想把一些数据可视化,所以我需要根据数值给我的数据框上色,使用渐变色,并且我想把这个结果导出到Excel里。

现在我遇到的问题是,它能导出灰色的部分,但不能导出渐变的黄色部分。你能帮我修改一下我的代码吗?或者你有没有其他的方法来完成这个任务?

我现在的代码是:

def highlight_negative(val):
if val > 1:
    if val <500:
        color = 'dimgrey'
    elif val >=500 and val < 1000: 
        color = 'lightgray'
    else:
        color = 'None'
else:
    color = None
    
return f'background-color: {color}'


def gradient_color(val):
    # Gradient colour yellow (low value) to white (high value)
    if val >=0 and val <=1:
        min_val = 0
        max_val = 1
        range_val = max_val - min_val
        if range_val == 0:
        # if all the values are equal - return white colour
            return 'background-color: rgb(255,255,255)'
        else:
        # Setting RGB component to gradient from yellow to white 
            r = 255
            g = 255
            b = int(255 * (max_val - val) / range_val)
    else:
        r = None
        g = None
        b = None
    return f'background-color: rgb({r},{g},{b})'

# Apply gradient and highlight design to DataFrame
styled_df = df.style.applymap(gradient_color, subset=df.columns[2:]).applymap(highlight_negative, subset=df.columns[2:]).format(precision=2)

styled_df.to_excel('styled_df.xlsx', engine='openpyxl')

1 个回答

0

使用条件格式并不会限制自动化的功能。
你不是在Pandas中给单元格上色再写入Excel,而是直接在Excel中上色,使用Openpyxl来应用条件格式。
这两者没有太大区别,除非你有特殊需要,要在包含样式的DataFrame中访问数据。
条件格式的一个好处是,如果你在Excel中手动更改了某些值,填充颜色会自动更新。

总之,你可以根据自己的情况选择更合适的方法。

正如@Vikas所提到的,如果你能提供你的数据框和期望的结果,那会更好,这样我可以根据你的代码猜测你的数据可能是什么样的。
看起来这个数据框里有数字值,而你想根据这些值来设置背景颜色:

  1. 值在0到1之间,背景颜色从白色渐变到黄色
  2. 值在1到500之间,背景颜色为深灰色
  3. 值在500到1000之间,背景颜色为浅灰色
  4. 值超过1000则不设置背景颜色

在这个例子中,我有一个包含各种值的数据框,覆盖了上面提到的四个范围。将数据框写入Excel后,我们使用Openpyxl来应用条件格式。

import pandas as pd
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule
from openpyxl.styles import PatternFill
from openpyxl.styles.differential import DifferentialStyle

df = pd.DataFrame({
    'ID': range(1, 5),
    'col1': [0.1, 0.99, 501, 0.01],
    'col2': [0.4, 1001, 0.6, 489],
    'col3': [10, 0.15, -0.67, 0.89],
    'col4': [0.35, 127, 0.40, 867]
})

excel_file = 'styled_df.xlsx'
sheet_name = 'Sheet1'

### Define Style colours
white_fill = PatternFill(start_color='FFFFFF', end_color='FFFFFF', fill_type='solid')
dim_grey_fill = PatternFill(start_color='696969', end_color='696969', fill_type='solid')
light_gray_fill = PatternFill(start_color='D3D3D3', end_color='D3D3D3', fill_type='solid')
### Conditional Format Range
cf_range = "B2:E5"

### Write the DataFrame to Excel
with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
    df.to_excel(writer, sheet_name=sheet_name, header=True, index=False)

    ws = writer.book[sheet_name]

    ### CF Rule1; Values greater than 1000 fill background with white (no colour)
    rule_def = CellIsRule(operator="greaterThan",
                       formula=[1000],
                       stopIfTrue=False)
    rule.dxf = DifferentialStyle(fill=white_fill)
    ws.conditional_formatting.add(cf_range, rule_def)

    ### CF Rule1; Values between > 1 and 500 fill background with dim_grey
    rule1 = CellIsRule(operator="between",
                       formula=[1.01, 500],
                       stopIfTrue=False)
    rule1.dxf = DifferentialStyle(fill=dim_grey_fill)
    ws.conditional_formatting.add(cf_range, rule1)

    ### CF Rule2; Values > 500 and 1000 fill background with light_gray
    rule2 = CellIsRule(operator='between',
                       formula=[500.01, 1000],
                       stopIfTrue=False)
    rule2.dxf = DifferentialStyle(fill=light_gray_fill)
    ws.conditional_formatting.add(cf_range, rule2)

    ### CF Rule3; Values 0 and 1 fill background with gradient from White (0) to Yellow (1)
    rule3 = ColorScaleRule(start_type='num', start_value=0.1, start_color='FFFFFFFF',
                           end_type='num', end_value=1, end_color='FFFFFF00')
    ws.conditional_formatting.add(cf_range, rule3)

Excel中的数据看起来是这样的
条件格式应用于B2:E5范围内的单元格。如前所述,如果你更改了某个值,背景颜色会自动更新以适应新的值。
在这里输入图片描述

撰写回答