I am trying to format a table, such that data in each column are formatted in a style depending on their values (similar to conditional formatting in spreadsheet programs).
Since pandas 0.17.1, it is easy to apply custom formatting to the data frame HTML representation using the styling api.
import pandas as pd
df = pd.DataFrame({
'correlation':[0.5, 0.1,0.9],
'p_value':[0.1,0.8,0.01]})
styled_df = df.style.apply(
lambda x: ['font-weight: bold; background-color: yellow'
if value <= 0.01 else '' for value in x])
styled_df
The output is rendered automatically in interfaces such as the Jupyter Notebook
and the string representation of the HTML can be returned with the render()
method.
print(styled_df.render())
correlation
p_value
0
0.5
0.1
1
0.1
0.8
2
0.9
0.01