Pandas 条件格式不显示背景颜色。 (没有错误)

Pandas conditional formatting not displaying background colors. (no errors)

我正在为这个项目使用 jupyter notebook。我正在尝试向我的数据框添加条件格式。我想给负数一个红色背景,给正数一个绿色背景,如果可能的话去掉行号。我尝试在底部使用的代码不会返回任何错误。

    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)

#conditional formatting highlight negative numbers red background and positive numbers green background in return data



def color_negative_red(value):
  """
  Colors elements in a dateframe
  green if positive and red if
  negative. Does not color NaN
  values.
  """

  if value < 0:
    background_color = 'red'
  elif value > 0:
    background_color = 'green'
  else:
    background_color = ''

  return 'background_color: %s' % background_color

df.style.applymap(color_negative_red, subset=['Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%']).format({
    'Close': '{:,.2f}'.format,
    'Daily%': '{:,.2f}%'.format,
    'WTD%': '{:,.2f}%'.format,
    'MTD%': '{:,.2f}%'.format,
    'QTD%': '{:,.2f}%'.format,
    'YTD%': '{:,.2f}%'.format,
})

输出:

想要用红色和绿色而不是黄色输出类似这样的输出:

在某些方面,这个特定的样式问题很简单。 CSS 属性 是 background-color 而不是 background_color.

唯一必要的更改是使样式正常工作:

return 'background-color: %s' % background_color

但是,关于一般方法,以及如何删除“行号”的问题,需要进行一些更改。

  1. 可以使用 str.endswith 之类的东西以编程方式过滤列,而不是手动输入列。在重新使用相同的列子集时,变量也很有用。
  2. 更常见的是创建一个代表所有样式的二维结构,例如 np.select 接受条件列表和输出列表。
  3. Styler.format可以是子集。因此,与其在字典中复制大量相同格式的字符串,不如利用这一点。
  4. Styler.hide_index方法可用于去除“行号”,也称为DataFrame索引。
import numpy as np


def color_negative_red(subset_df):
    # Create Styles based on multiple conditions with np.select
    return np.select(
        [subset_df < 0, subset_df > 0],
        ['background-color: red', 'background-color: green'],
        default=''
    )


# Select Subset of columns
cols = df.columns[df.columns.str.endswith('%')]
# This can also be hard-coded
# cols = ['Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%']
(
    df.style.apply(
        color_negative_red, subset=cols, axis=None
    ).format(
        # This can be used to set general number styles without a fmt string
        precision=2, thousands=",", subset='Close'
    ).format(
        # Apply percent format to subset of cols
        '{:,.2f}%', subset=cols
    ).hide_index()  # To remove the "row numbers" hide the index
)


使用的示例数据帧:

df = pd.DataFrame({'Stock': ['SPY', 'TLT', 'XLY', 'XLF', 'XLV', 'XLK', 'XLP', 'XLI', 'XLB', 'XLE', 'XLU', 'XLRE', 'XLC'], 'Close': [453.0799865722656, 148.17999267578125, 183.52000427246094, 38.06999969482422, 136.85000610351562, 159.36000061035156, 72.83000183105469, 104.58999633789062, 85.37000274658203, 48.619998931884766, 69.48999786376953, 48.72999954223633, 85.47000122070312], 'Daily%': [-0.024275881759957655, -0.9094561130207558, -0.05990339673614984, -0.6264726438619272, 0.10973603410557096, 0.39690348375861295, -0.12341791024475374, -0.6081982311376585, -0.66325305868224, -0.5726024238382843, -0.8277463016708558, 0.0, 0.0], 'WTD%': [0.18795205211694732, -1.1144566965053964, 0.1692033989594774, -0.9882992472694656, 1.078371165114885, -0.2128968969240593, 1.0124873403369272, -0.20038807991586702, -0.5706939905500718, -0.22573488894909668, 1.2678447717357961, 2.8059028977694966, 0.19929444649862676], 'MTD%': [0.28331093711392863, -0.47686662420427856, -0.06534258200082742, -0.28811055388244855, 1.1829989674792052, 0.2894944817725163, 0.26156723981653324, 0.4610467051436526, -0.023418015235201397, 1.9500950554754906, 0.07199801354481171, 0.4742258602810889, -0.6740288326379547], 'QTD%': [5.262178352321592, 2.7814348045817643, 2.2053947247214483, 2.9475396594933923, 7.6965502732190245, 7.741191714387993, 4.4008021800644235, 1.4156880862558818, 3.1536980944675, -11.293563740764009, 8.714017294090489, 9.481018602199223, 4.781171436152855], 'YTD%': [22.855819321112786, -5.941348869649508, 15.117304215482205, 30.914717313288243, 21.15981390085853, 24.597340663914796, 9.157674608158786, 21.039222202640808, 19.065559804985433, 28.082192056143985, 13.69437021949676, 37.73317713704715, 28.56497729371572]})