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

Jupyter中Pandas条件格式无报错但不显示背景色如何解决

问题修复方案

核心错误原因

你自定义的样式函数返回的CSS属性名写错了,CSS中背景色的标准属性是background-color(中划线分隔),而非你写的background_color(下划线分隔),因此样式规则无法被渲染识别,导致背景色不生效。

隐藏行号实现方法

Pandas的Styler对象自带.hide()方法,指定axis='index'即可隐藏左侧行号。

修正后完整代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader as data

tickers = ['SPY', 'TLT', 'XLY', 'XLF', 'XLV', 'XLK', 'XLP', 'XLI', 'XLB', 'XLE', 'XLU', 'XLRE', 'XLC']
df_list = []
for ticker in tickers:
    prices = data.DataReader(ticker, 'yahoo', '2021')['Close']

    # get all timestamps for specific lookups
    today = prices.index[-1]
    yest= prices.index[-2]
    start = prices.index[0]
    week = today - pd.tseries.offsets.Week(weekday=0)
    month = today - pd.tseries.offsets.BMonthBegin()
    quarter = today - pd.tseries.offsets.BQuarterBegin(startingMonth=1)

    # calculate percentage changes
    close = prices[today]
    daily =  (close - prices[yest]) / prices[yest]*100
    wtd = (close - prices[week]) / prices[week]*100
    mtd = (close - prices[month]) / prices[month]*100
    qtd = (close - prices[quarter]) / prices[quarter]*100
    ytd = (close - prices[start]) / prices[start]*100

    # create temporary frame for current ticker
    df = pd.DataFrame(data=[[ticker, close, daily, wtd, mtd, qtd, ytd]],
                      columns=['Stock', 'Close', 'Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%'])
    df_list.append(df)

# stack all frames
df = pd.concat(df_list, ignore_index=True)

# 修正后的条件格式函数
def color_negative_red(value):
  """
  对DataFrame元素设置背景色:正数绿色、负数红色,NaN不染色
  """
  if value < 0:
    color = 'red'
  elif value > 0:
    color = 'green'
  else:
    color = ''
  # 这里修改为正确的CSS属性名 background-color
  return f'background-color: {color}'

# 链式调用添加hide方法隐藏行号
df.style.applymap(color_negative_red, subset=['Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%'])\
  .hide(axis='index')\
  .format({
    'Close': '{:,.2f}'.format,
    'Daily%': '{:,.2f}%'.format,
    'WTD%': '{:,.2f}%'.format,
    'MTD%': '{:,.2f}%'.format,
    'QTD%': '{:,.2f}%'.format,
    'YTD%': '{:,.2f}%'.format,
})

如果修改后仍然无法正常渲染,检查Jupyter Notebook是否禁用了HTML渲染,确保上述Styler对象是Cell的最后一行返回值,即可自动触发渲染。

内容的提问来源于stack exchange,提问作者Jason Hanner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:18:04