Reputation: 345
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?
Upvotes: 1
Views: 1835
Reputation: 150735
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:
Upvotes: 1
Reputation: 862641
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
Upvotes: 3