1

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.

  • Highlight where? Are you exporting the results to a spreadsheet? Are you using Jupyter notebooks? – Mortz May 26 '22 at 14:46
  • higlight rows.jupyternotebooks – donald smith May 26 '22 at 14:46
  • any suggestions or inputs? – donald smith May 26 '22 at 14:54
  • I could find this with a search - https://jupyterbook.org/en/stable/content/code-outputs.html – Mortz May 26 '22 at 15:24
  • It sounds like you want [Pandas styling](https://pandas.pydata.org/pandas-docs/version/1.1/user_guide/style.html#Styling) that is referenced in the link Mortz provides. Some of those stylings even will transfer to Excel so that you can have them in a spreadsheet as well without needing to do anything else downstream inside Excel. – Wayne May 26 '22 at 15:41

1 Answers1

0

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

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52