如何在Pandas Style中基于另一表格样式显示文本单元格内容
如何为文本表格应用基于另一数值表格的背景渐变样式
需求:在表格单元格中显示文本内容,同时使用pandas.Styler.background_gradient函数,基于另一数值表格的数值为对应单元格应用背景渐变颜色。
示例代码与数据
import pandas as pd import numpy as np from faker import Faker fake = Faker() # 生成示例文本表格 text = pd.DataFrame(np.random.randint(5, 15, [4, 3]), columns=list('ABC')) text = text.applymap(fake.text) # 用于确定颜色的数值表格 importancy = text.copy() importancy[:] = np.random.randint(0, 100, text.shape) importancy = importancy.astype(int) # 需结合的两个输出:文本表格、数值表格的渐变样式 text importancy.style.background_gradient(cmap='Greens').format('')
目标文本表格示例:
A B C 0 Whose. Health. Pass black. 1 Only want. Most. Seek. 2 Road. Indeed. Certain. 3 Explain. Son high. Ahead.
预期效果:文本表格的每个单元格根据对应数值表格的数值大小,呈现从浅绿到深绿的渐变背景(数值越大颜色越深)。
已尝试的方法及问题
- 使用
style.export():将样式应用到文本表格时,会重新基于文本表格的数值计算颜色,不符合需求。 - 修改
style.data:执行style = importancy.style.background_gradient(cmap='Greens'); style.data[:] = text后,修改数据会触发颜色重新评估,原有渐变样式失效。 - 手动构建HTML表格:通过
apply函数添加样式,但无法完整导出background_gradient包含的所有配置(如最小值、最大值映射、空值处理等)。
解决方案
通过先提取数值表格生成的渐变样式,再将样式直接应用到文本表格,既保留原样式配置,又显示文本内容。
方法一:提取HTML样式后应用
import pandas as pd import numpy as np from faker import Faker from bs4 import BeautifulSoup fake = Faker() # 生成文本与数值表格 text = pd.DataFrame(np.random.randint(5, 15, [4, 3]), columns=list('ABC')) text = text.applymap(fake.text) importancy = text.copy() importancy[:] = np.random.randint(0, 100, text.shape) importancy = importancy.astype(int) # 生成数值表格的渐变样式并提取背景色 style_obj = importancy.style.background_gradient(cmap='Greens') html = style_obj.render() soup = BeautifulSoup(html, 'html.parser') cells = soup.find_all('td') bg_colors = [cell.get('style').split(':')[1].strip() for cell in cells] bg_color_matrix = np.array(bg_colors).reshape(text.shape) # 定义样式应用函数 def set_bg_color(val, row_idx, col_idx): return f'background-color: {bg_color_matrix[row_idx][col_idx]}' # 为文本表格应用样式 text_styled = text.style.applymap(lambda val, r, c: set_bg_color(val, r, c), axis=None) text_styled
方法二:利用Styler的导出/导入机制
import pandas as pd import numpy as np from faker import Faker fake = Faker() # 生成文本与数值表格 text = pd.DataFrame(np.random.randint(5, 15, [4, 3]), columns=list('ABC')) text = text.applymap(fake.text) importancy = text.copy() importancy[:] = np.random.randint(0, 100, text.shape) importancy = importancy.astype(int) # 导出数值表格的样式配置 style_obj = importancy.style.background_gradient(cmap='Greens') exported_style = style_obj.export() # 创建文本表格的Styler并应用导出的样式 text_styled = text.style for cell_style in exported_style['cellstyle']: row, col = cell_style['row'], cell_style['col'] text_styled.set_properties( **{'background-color': cell_style['props']['background-color']}, subset=pd.IndexSlice[row, col] ) text_styled
两种方法均保留了background_gradient生成的完整样式逻辑,同时让文本表格显示指定内容。
内容的提问来源于stack exchange,提问作者lisrael1
相关产品推荐
相关产品推荐

