'Pandas: apply background and font style in one go

Sounds simples, but I cannot find the correct way to do it.

my function below, applies only the style for background or for font, and I cannot find way to apply both...

Please advise how to apply in one go 'font-weight: bold' and 'background-color: #e5e5e5':

def color(df_):
    # Color rows grey and make text bold  where "Subtotal" is present
    styles_df = pd.DataFrame('', index=df_.index, columns=df_.columns)
    styles_df.loc[df_.PIN == 'Subtotal', :] = 'font-weight: bold'
    styles_df.loc[df_.PIN == 'Subtotal', :] = 'background-color: #e5e5e5'
    return styles_df

I have tried different options of the syntax without any luck (just few below) :)

styles_df.loc[df_.PIN == 'Subtotal', :] = (** {'font-weight: bold', 'background-color: #e5e5e5'})

or simple

styles_df.loc[df_.PIN == 'Subtotal', :] = 'font-weight: bold' and  'background-color: #e5e5e5'

Does not seem to work.

Update and Solution: based on @Quang Hoang example I ended up with the code below. the string should look like that ['background-color: #e5e5e5; font-weight: bold']:

def color(df_):
    # Color rows yellow where there are any 0 values across rows - for Adjustment sheet
    styles_df = pd.DataFrame('', index=df_.index, columns=df_.columns)
    styles_df.loc[df_.Hours == 0, :] = 'background-color: yellow'
    styles_df.loc[df_.PIN == 'Subtotal', :] = ['background-color: #e5e5e5; font-weight: bold']
    return styles_df

later saving to excel:

with pd.ExcelWriter(FilePath) as writer:
        df_subtotals.style.apply(color, axis=None).to_excel(writer, index=False, sheet_name='Site Adjustments')
        df_timesheet.style.apply(colorTS, axis=None).to_excel(writer, index=False, sheet_name=proj_num)


Solution 1:[1]

You can apply function on the rows like this:

def color(row):
    if row['a'] == 1: 
        return ['font-weight: bold; background-color: green'] * len(row)

data.style.apply(color, axis=1)

Output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quang Hoang