You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Pandas DataFrame指定单元格设置加粗样式并整合现有格式?

为指定DataFrame单元格设置加粗样式的解决方案

问题背景

现有基于字典创建的Pandas DataFrame,已实现负数标红、正数标绿的样式逻辑,需给**(0,0)、(0,2)、(0,4)**三个单元格单独添加加粗样式,且要与现有样式兼容。

现有代码

  1. 创建DataFrame的数据源:
data = {'BTC': {'PNL': 834.8485, 'FUNDING': 575.20837762, 'DELTA VOL': 18845436.3535, 'HEDGE VOL': 16444662.545, 'OI': 4598885.7407, 'DEFICIT': 149.35084}, 'BTC 4HR': {'PNL': 76.2125, 'FUNDING': 197.52681642, 'DELTA VOL': 1999585.538, 'HEDGE VOL': 1729156.5247, 'OI': None, 'DEFICIT': None}, 'ETH': {'PNL': -661.112, 'FUNDING': -218.42574899, 'DELTA VOL': 10720104.9915, 'HEDGE VOL': 10088271.477, 'OI': 552973.992, 'DEFICIT': 61.9926}, 'ETH 4HR': {'PNL': 65.331, 'FUNDING': 23.57589308, 'DELTA VOL': 373668.3985, 'HEDGE VOL': 356349.724, 'OI': None, 'DEFICIT': None}, 'TOTAL': {'PNL': 2859.98348042, 'FUNDING': 871.26688115, 'DELTA VOL': 33607091.07200743, 'HEDGE VOL': 30570729.07912772, 'OI': 6019831.030358, 'DEFICIT': 9250.907426}, 'TOTAL 4HR': {'PNL': 177.84871257, 'FUNDING': 246.41302914, 'DELTA VOL': 2881419.73415996, 'HEDGE VOL': 2592306.47723815, 'OI': None, 'DEFICIT': None}}
  1. 转换为DataFrame:
df1 = pd.DataFrame(data).T
  1. 颜色样式函数:
def color_negative_red(val):
    try:
        if val < 0:
            color = 'red'
        elif val>0:
            color='green'
        return 'color: %s' % color
    except:
        return 'color: black'
  1. 现有样式设置(注:原代码中apply(styler)为笔误,修正为applymap(color_negative_red)):
df1=df1.style.applymap(color_negative_red).set_caption("Futures Risk Monitor").format("{:20,.0f}").set_table_styles([{
    'selector': 'thead th',
    'props': [('text-align', 'center')]
}])
display(df1)

解决方案

通过style.apply结合自定义函数,可针对特定单元格添加加粗样式,且与现有样式叠加生效。

步骤1:定义加粗样式函数

创建函数判断单元格位置是否在目标列表中,是则返回加粗样式:

def bold_specific_cells(x):
    # 目标单元格的(行索引, 列索引)
    target_cells = [(0, 0), (0, 2), (0, 4)]
    # 创建空样式DataFrame,与原DataFrame结构一致
    styles = pd.DataFrame('', index=x.index, columns=x.columns)
    # 为目标单元格设置加粗
    for row, col in target_cells:
        styles.iloc[row, col] = 'font-weight: bold'
    return styles

步骤2:整合所有样式

在原有样式代码基础上,叠加加粗样式:

styled_df = df1.style.applymap(color_negative_red)\
                      .apply(bold_specific_cells, axis=None)\
                      .set_caption("Futures Risk Monitor")\
                      .format("{:20,.0f}")\
                      .set_table_styles([{
                          'selector': 'thead th',
                          'props': [('text-align', 'center')]
                      }])
display(styled_df)

关键说明

  • applymap负责逐元素应用颜色样式,apply结合axis=None负责针对整个DataFrame的位置设置加粗样式,两者样式会合并生效。
  • 目标单元格索引对应转换后的DataFrame:第一行(索引0)的第1、3、5列(列索引0、2、4),即BTC行的PNL、DELTA VOL、OI三个单元格。

内容的提问来源于stack exchange,提问作者Madan Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:34:54