[英]change Pandas Row background colour and Font Colors based on 2 different conditions
如果Rising
为 False,我有一个代码可以更改单元格背景颜色。 如果Index
值为Nifty 50
我想将Cell Color 更改为 Green 。
因此,如果任何行来自Nifty 50
但Rising
为 False,则Nifty 50
单元格应位于该 Only 单元格的绿色背景中,所有其他单元格应为红色。
这就是我希望 Dataframe 的样子:如果Rising
为False or 0
则整行为红色。 根据是否来自Nifty-50/100/200
更改Index
颜色
改变颜色的代码如下:
def highlight_falling(s, column:str):
'''
Highlight The rows where average is falling
args:
s: Series
column: Column name(s)
'''
is_max = pd.Series(data=False, index=s.index)
is_max[column] = s.loc[column] == True
return ['' if is_max.any() else 'background-color: #f7a8a8' for v in is_max]
picked.style.apply(highlight_falling, column=['Rising'], axis=1) # picked is the DF
在这里,我想将 50,100,200,500 单元格的索引指定为[Green,Blue,Magenta. White]
[Green,Blue,Magenta. White]
(只是棕褐色的例子)
我们可以使用Series.map
将列中的值与新的颜色样式相关联。 然后我们将在行样式之后应用Index
列样式以覆盖之前放置的红色:
def highlight_falling(f: pd.DataFrame, column: str):
# Create an Empty DataFrame
f_styles = pd.DataFrame('', index=f.index, columns=f.columns)
# Apply Styles based on column. (Set red where not Truthy)
f_styles.loc[~(f[column].astype(bool)), :] = 'background-color: #f7a8a8'
return f_styles
def highlight_nifty(s: pd.Series):
return 'background-color: ' + s.map({
'Nifty 50': 'green',
'Nifty 100': 'blue',
'Nifty 200': '#888888'
}) # Map to colour codes
# Save Styler To Re-use (can also Chain)
styler = picked.style
# Apply Row Colour (Do not pass column as List[str] use str!!)
styler.apply(highlight_falling, column='Rising', axis=None)
# Apply Index Column Colours
styler.apply(highlight_nifty, subset='Index')
如果要指定颜色列表,也可以使用dict
和zip
创建映射字典,可以使用unique
从 Index 列获取所有唯一值,然后可以使用natsorted
对它们进行排序(安全的字母数字排序):
from natsort import natsorted
from typing import List
def highlight_falling(f: pd.DataFrame, column: str):
# Create an Empty DataFrame
f_styles = pd.DataFrame('', index=f.index, columns=f.columns)
# Apply Styles based on column. (Set red where not Truthy)
f_styles.loc[~(f[column].astype(bool)), :] = 'background-color: #f7a8a8'
return f_styles
def highlight_nifty(s: pd.Series, colours: List[str]):
return 'background-color: ' + s.map(
# Build Colour Map Dynamically based on unique values from column
dict(zip(natsorted(s.unique()), colours))
) # Map to colour codes
# Save Styler To Re-use (can also Chain)
styler = picked.style
# Apply Row Colour (Do not pass column as List[str] use str!!)
styler.apply(highlight_falling, column='Rising', axis=None)
# Apply Index Column Colours
styler.apply(highlight_nifty, subset='Index',
colours=['green', 'blue', '#888888'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.