Jupyter Notebook中基于唯一列与Color Mode列实现明暗色迭代着色
DataFrame分组明暗着色与分隔实现方案
需求描述
- 在Jupyter Notebook中,基于已合并并包含
Color Mode列的DataFrame实现以下效果:Color Mode值为'a'对应深色背景,'b'对应浅色背景- 按
x1列的唯一值分组,每组内根据Color Mode实现明暗交替着色 - 每个
x1分组后添加空行,实现视觉分隔
原始示例数据
基础示例DataFrame
import pandas as pd from itertools import cycle df1 = pd.DataFrame({'x1':['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd'], 'x2':['3','4','8','0','11','1','15','5','67','3','1','4','5','88','9','3','7','2','3','43','34','56','96','26'], 'Color Mode':['a','a','b','b','b','b','a','a','a','a','b','b','a','b','b','b','b','b','b','b','a','a','a','b']})
扩展示例DataFrame
new_df1 = pd.DataFrame({'x1':['axe', 'axe', 'axe', 'axe', 'axe', 'axe', 'bench', 'bench', 'bench', 'bench', 'bench', 'bench', 'crunch', 'crunch', 'crunch', 'crunch', 'crunch', 'crunch', 'crunch', 'crunch', 'deed', 'deed', 'deed', 'deed'], 'x2':['Bob','Bob','Bob','Bob','Bob','Bob','Leo','Leo','Leo','Leo', 'Leo','Leo','Jamie','Jamie','Jamie','Jamie','Jamie','Jamie','Jamie','Jamie', 'John','John','John','Luke'], 'Price':['3.00','3.00','3.00','3.00','3.00','3.00','15.00','80.00','15.00','15.00', '15.00','15.00','4.00','4.00','4.00','68.00','4.00','4.00','39.00','4.00', '5.00','5.00','5.00','27.00'], 'Color Mode':['a','a','b','b','b','b','a','a','a', 'a','b','b','a','b','b','b','b','b', 'b','b','a','a','a','b']})
现有代码问题
当前Color_Unique函数未区分Color Mode的明暗逻辑,也未实现分组后空行分隔,无法达到预期的分组明暗交替+视觉分隔效果。
解决方案代码
步骤1:添加分组分隔空行
def add_group_separators(df): # 按x1分组,每组末尾插入空行 grouped = df.groupby('x1', group_keys=False) df_with_sep = grouped.apply(lambda g: pd.concat([g, pd.DataFrame([[None]*len(g.columns)], columns=g.columns)])) # 移除最后一行多余空行,重置索引 return df_with_sep.iloc[:-1].reset_index(drop=True) # 处理两个示例数据 df1_with_sep = add_group_separators(df1) new_df1_with_sep = add_group_separators(new_df1)
步骤2:实现分组明暗着色逻辑
def color_groups_with_mode(df): # 定义基础深色列表 base_colors = ['#ADD8E6', '#90ee90', '#FFD580', '#CBC3E3', '#D3D3D3', '#C4A484'] color_cycle = cycle(base_colors) # 给每个x1分组分配专属基础深色 x1_unique = df['x1'].dropna().unique() x1_color_map = {x1_val: next(color_cycle) for x1_val in x1_unique} # 初始化样式矩阵 styles = pd.DataFrame('', index=df.index, columns=df.columns) for idx, row in df.iterrows(): x1_val = row['x1'] # 空行跳过着色 if pd.isna(x1_val): continue base_color = x1_color_map[x1_val] if row['Color Mode'] == 'a': # 'a'使用基础深色 bg_style = f'background-color: {base_color}' else: # 'b'使用对应浅色(通过添加透明度实现明暗区分) bg_style = f'background-color: {base_color}80' styles.loc[idx, :] = bg_style return styles
步骤3:应用样式并展示
# 展示基础示例效果 styled_df1 = df1_with_sep.style.apply(color_groups_with_mode, axis=None) display(styled_df1) # 展示扩展示例效果 styled_new_df1 = new_df1_with_sep.style.apply(color_groups_with_mode, axis=None) display(styled_new_df1)
效果说明
- 每个
x1分组内,Color Mode为'a'的行使用分配的基础深色,'b'的行使用对应浅色(带透明度),实现明暗交替 - 每个
x1分组后自动插入空行,视觉上清晰区分不同分组
内容的提问来源于stack exchange,提问作者b_ham
相关产品推荐
相关产品推荐

