Home > OS >  Highlight rows in dataframe based on condition
Highlight rows in dataframe based on condition

Time:05-27

I have dataframe df :

id    product. 2021-01.   2021-02  2021-03
caw2.  A.        12.         31       10
ssca.  B         12.         13       34
dsce.  c         11          13       32

I want to highlight records with red where last column(2021-03) is less than previous one(2021-02) and with green where last column is greater than previous one.

I am running the code in a Jupyter Notebook.

CodePudding user response:

You can try

def highlight(df):
    m1 = df['2021-03'] > df['2021-03'].shift()
    m2 = df['2021-03'] < df['2021-03'].shift()

    color = 'background-color: {}'.format

    style = pd.Series([color('')]*df.shape[0])
    style = style.mask(m1, color('green'))
    style = style.mask(m2, color('red'))
    style = pd.concat([style]*df.shape[1], axis=1)
    style.columns = df.columns
    style.index = df.index

    return style

s = df.style.apply(highlight, axis=None)

enter image description here

  • Related