【发布时间】:2021-11-02 15:24:50
【问题描述】:
我正在为这个项目使用一个 jupyter 笔记本。我正在尝试向我的数据框添加条件格式。我想给负数一个红色背景,给正数一个绿色背景,如果可能的话,去掉行号。我试图在底部使用的代码不会返回任何错误。
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,
})
输出:
希望输出类似这样的红色和绿色而不是黄色:
【问题讨论】:
标签: python pandas finance pandas-datareader pandas-styles