I want to apply some styles to whole row and I am doing like this.
df = pd.DataFrame({
'correlation':[0.5, 0.1,0.9],
"volume": [38,45,10]})
def highlight_col(x):
#copy df to new - original data are not changed
df = x.copy()
#set by condition
mask = df['volume'] <= 40
df.loc[mask, :] = 'background-color: yellow'
df.loc[~mask,:] = 'background-color: ""'
return df
df.style.apply(highlight_col, axis=None)
But I see that nothing happens. Can somebody guide me in the right direction please?
PS: I believe it should call ´highlight_col´ function but it wont.
Take a look to the styling guide provided by pandas.
The function
df.style.apply()return aStylerobject, so your dataframe don't contain the styiling but you need to save the output of theapplyfunction and useto_excel()on this output. In your code I have done it directly without saving.I made some tests editing your code, take a look:
This produce the following output:
Setting the color to:
df.loc[~mask,:] = "background-color: ''"generate a warning:CSSWarning: Unhandled color format: "''"and set the color to black, that could be solved changing the line asdf.loc[~mask,:] = ''. This will produce:In the case you really want the black row, is better to specify it with
"background-color: black".You can also change the line
df.style.apply(highlight_col, axis=None).to_excel('test.xlsx')with:It will produce the same output:
To get the
Styleras HTML format you can simply use therender()function and print the output:You can also use
_repr_html_:Output:
In the case you want to change the style only for the cell and not for the row, take a look to this possible solution:
Output: