Bold a Data frame row in pandas with Styler

Viewed 376

I have a mock Data frame which looks something like this.

df = pd.DataFrame({'name':['a','b','c'],
                   'sex':['M','F','F'],
                  'percentage': [98,99,99.5]})

What I am trying to do is, if the sex is 'M', I am trying to bold all the elements of the row. And this is how I am trying to do this

def bold_style(val):
    if val['sex'] == 'M':
        return "font-weight: bold"

df.style.apply(bold_style,axis = 1)

My understanding is that, when I pass axis = 1, the function searches by each row, returning the style wherever the condition is satisfied. But this doesn't seem to be the case. Instead, I get this error.

ValueError: Function <function bold_style at 0x000002369E256820> returned the wrong shape. Result has shape: (3,) Expected shape: (3, 3)

Can anyone help me understand why this is happening?

Thanks

1 Answers

Create DataFrame of styles with set font by condition in DataFrame.mask:

def bold_style(val):
    f = "font-weight: bold" 
    #condition
    m = val["sex"] == 'M'
    # DataFrame of styles
    df1 = pd.DataFrame('', index=val.index, columns=val.columns)
    # set columns by condition
    df1 = df1.mask(m, f)
    return df1

df.style.apply(bold_style, axis=None)
Related