我想要可视化一些数据,因此我需要根据值以渐变颜色为我的数据框着色,并且我想将其导出到 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')
使用条件格式不会限制自动化。
您只需使用 Openpyxl 为 Excel 中的单元格着色,而不是为 Pandas 中的单元格着色并写入 Excel。
除非您需要访问包含样式的 DataFrame,否则它应该没有任何不同。
条件格式还有一个优点,如果您出于某种原因需要在 Excel 中手动更改任何值,那么颜色更改将自动进行。
无论如何,您可以选择最适合您的场景的方法。
正如 @Vikas 指出的,如果您提供数据框和预期结果会更好,所以我根据您的代码猜测您的数据可能是什么样子。
看来 DF 有数值,并且您希望背景颜色基于;
在此示例中,我有一个包含各种值的 DataFrame 来覆盖上面的 4 个范围。将 DF 写入 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
rule = CellIsRule(operator="greaterThan",
formula=[1000],
stopIfTrue=False)
rule.dxf = DifferentialStyle(fill=white_fill)
ws.conditional_formatting.add(cf_range, rule)
### CF Rule1; Values between 1 and 500 fill background with dim_grey
rule1 = CellIsRule(operator="between",
formula=[1, 500],
stopIfTrue=False)
rule1.dxf = DifferentialStyle(fill=dim_grey_fill)
ws.conditional_formatting.add(cf_range, rule1)
### CF Rule2; Values 500 and 100 fill background with light_grey
rule2 = CellIsRule(operator='between',
formula=[500, 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 中的数据将如下所示
CF 适用于 B2:E5 范围内的单元格。如前所述,如果您更改值,背景颜色将更新以适应。