Home > Blockchain >  How to colorize the cell in column? Pandas, pygsheets
How to colorize the cell in column? Pandas, pygsheets

Time:10-30

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

CodePudding user response:

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)
  • Related