1

I got dataframe with 3 columns : sku/price_1/price_2 How to color a cell in price_2 if it is less than in price_1? what i already tried:

    def highlight_late(s):
        color = ['background-color: red' if s['price_2'] < s['price_1'] else 
        'background-color: white' for s_ in s ]
        return color
df = myDataframe.style.apply(highlight_late,axis=1)

i also try with subset='price_2' but it didnt work, returns me keyerror 'price_1' but if i not use subset, its works but colorize all row. and how to color in google sheet with pygsheets ? TABLE

1 Answers1

0

I think the simplest way is to create a DataFrame of styles by conditions, set column(s) that you need in your function with Styler.apply with axis=None:

print(df)
       SKU  price_1  price_2
0  SKU_123     5110   5110.0
1  SKU_124     4730      NaN
2  SKU_125     4490      NaN
3  SKU_126     4730      NaN
4  SKU_127     5530   5500.0
5  SKU_128  1245300      NaN

def highlight_late(x):
    c1 = 'background-color: red'
    # condition
    m = x['price_2'] < x['price_1']
    # empty DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)

    # in case you need to set the background white
    # df1 = pd.DataFrame('background-color: white', index=x.index, columns=x.columns)

    # set column price_2 by condition
    df1.loc[m, 'price_2'] = c1
    # set column SKU by condition
    # df1.loc[m, 'SKU'] = c1
    return df1

df.style.apply(highlight_late, axis=None).to_excel('file.xlsx', index=False)
Troll
  • 1,895
  • 3
  • 15
  • 34
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Hi, pycharm tell me Expected type '(...) -> Styler', got '(x: {__getitem__, index, columns}) -> DataFrame' instead in df.style.apply(highlight_late, axis=None), what is wrong? – Yaroslav Butorin Oct 29 '21 at 06:23
  • @YaroslavButorin - Added export to excel, for me working perfectly. – jezrael Oct 29 '21 at 06:59
  • myDF.style.apply(highlight_late, axis=None).to_excel('test.xlsx') - Finally! its works, thanks so much. But why its not works then i do it in two strings ? Like: myDF.style.apply(highlight_late, axis=None) myDF.to_excel('test.xlsx') – Yaroslav Butorin Oct 29 '21 at 07:18
  • @YaroslavButorin - then need `styles = myDF.style.apply(highlight_late, axis=None)` and `styles.to_excel('test.xlsx')` – jezrael Oct 29 '21 at 07:20