pandas: HTML output with conditional formatting

后端 未结 2 1599
走了就别回头了
走了就别回头了 2020-12-29 04:18

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).

2条回答
  •  一向
    一向 (楼主)
    2020-12-29 04:21

    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

提交回复
热议问题