Pandas: HTML Output With Conditional Formatting
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). How can
Solution 1:
You can use the DataFrame to_html
method, which comes with formatters
argument.
An easier solution would be to surround by <span class="significant">
and </span>
, (rather than *
). Note: by default this will be escaped (i.e. <
becomes <
) so you will need to use the escape=False
argument.
Solution 2:
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())
<style type="text/css" >
#T_4e49b9da_8451_11e8_9166_605718a99a7frow2_col1 {
font-weight: bold;
background-color: yellow;
font-weight: bold;
background-color: yellow;
}</style>
<table id="T_4e49b9da_8451_11e8_9166_605718a99a7f" >
<thead> <tr>
<th class="blank level0" ></th>
<th class="col_heading level0 col0" >correlation</th>
<th class="col_heading level0 col1" >p_value</th>
</tr></thead>
<tbody> <tr>
<th id="T_4e49b9da_8451_11e8_9166_605718a99a7flevel0_row0" class="row_heading level0 row0" >0</th>
<td id="T_4e49b9da_8451_11e8_9166_605718a99a7frow0_col0" class="data row0 col0" >0.5</td>
<td id="T_4e49b9da_8451_11e8_9166_605718a99a7frow0_col1" class="data row0 col1" >0.1</td>
</tr> <tr>
<th id="T_4e49b9da_8451_11e8_9166_605718a99a7flevel0_row1" class="row_heading level0 row1" >1</th>
<td id="T_4e49b9da_8451_11e8_9166_605718a99a7frow1_col0" class="data row1 col0" >0.1</td>
<td id="T_4e49b9da_8451_11e8_9166_605718a99a7frow1_col1" class="data row1 col1" >0.8</td>
</tr> <tr>
<th id="T_4e49b9da_8451_11e8_9166_605718a99a7flevel0_row2" class="row_heading level0 row2" >2</th>
<td id="T_4e49b9da_8451_11e8_9166_605718a99a7frow2_col0" class="data row2 col0" >0.9</td>
<td id="T_4e49b9da_8451_11e8_9166_605718a99a7frow2_col1" class="data row2 col1" >0.01</td>
</tr></tbody>
</table>
Post a Comment for "Pandas: HTML Output With Conditional Formatting"