Coloring Single Column of Pandas Dataframe.to_html()

前端 未结 2 1607
一个人的身影
一个人的身影 2021-01-17 05:20

Before this is marked as duplicate, I have tried the code from the following topics and none has worked for me thus far:

[Colouring one column of pandas dataframe ]

2条回答
  •  梦谈多话
    2021-01-17 05:47

    Let's try this:

    import pandas as pd
    import numpy as np
    
    np.random.seed(24)
    df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
    
    df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
                   axis=1)
    df.iloc[0, 2] = np.nan
    
    def highlight_column(s, col):
        return ['background-color: #d42a2a' if s.name == col else '' for v in s.index]
    
    df.style.apply(highlight_column, col = 'B')
    

    Output:

提交回复
热议问题