1

I have the following dataframe comp:

    time        first_max   name             second_max name.1      Perceived OoM.1 Perceived OoM.2
0   0.000000    18          shoulder_center  9          right_hip   shoulder_center shoulder_center
1   0.010000    18          shoulder_center  9          right_hip   shoulder_center shoulder_center
2   0.020000    18          right_hip        9          right_hip   shoulder_center right_hip
3   0.030000    18          shoulder_center  9          right_hip   shoulder_center right_hip

And I have this function that highlights a whole row based on whether name == Perceived OoM.1:

def highlight_col(x):
    df = x.copy()
    mask = df['name'] == df['Perceived OoM.1']
    df.loc[mask, :] = 'background-color: yellow'
    df.loc[~mask,:] = 'background-color: ""'
    return df

comp.style.apply(highlight_col, axis=None)

But, I want to figure out a way to colour a whole row another colour if name == Perceived OoM.2. Basically, I want the row to be yellow if name == Perceived OoM.1 otherwise the row to be blue if name == Perceived OoM.2.

But I can't seem to work that condition into my function.

Any help?

2 Answers 2

3

Create another mask and pass same way, also for default empty values is used DataFrame constructor:

def highlight_col(x):
    df = pd.DataFrame('', index=x.index, columns=x.columns)
    mask1 = x['name'] == x['Perceived OoM.1']
    mask2 = x['name'] == x['Perceived OoM.2']
    df.loc[mask1, :] = 'background-color: yellow'
    df.loc[mask2, :] = 'background-color: blue'
    return df
Sign up to request clarification or add additional context in comments.

1 Comment

@Oam - Sorry, there was typo for both mask, need compare x like x['name'] == x['Perceived OoM.1'], not df['name'] == df['Perceived OoM.1']
1

Another way is to define a function so you can apply on rows:

def highlight(x):
    color = 'background-color:yellow' if  x['name']==x['Perceived OoM.1']\
            else 'background-color: green' if x['name']==x['Perceived OoM.2']\
            else ''
    return [color]*len(x)

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

Output:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.