繁体   English   中英

根据 2 种不同条件更改 Pandas Row 背景颜色和字体颜色

[英]change Pandas Row background colour and Font Colors based on 2 different conditions

如果Rising为 False,我有一个代码可以更改单元格背景颜色。 如果Index值为Nifty 50我想将Cell Color 更改为 Green 。

因此,如果任何行来自Nifty 50Rising为 False,则Nifty 50单元格应位于该 Only 单元格的绿色背景中,所有其他单元格应为红色。

这就是我希望 Dataframe 的样子:如果RisingFalse 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')

样式表


如果要指定颜色列表,也可以使用dictzip创建映射字典,可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM