Coloring Single Column of Pandas Dataframe.to_html()

前端 未结 2 1579
一个人的身影
一个人的身影 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:

    0 讨论(0)
  • 2021-01-17 05:55

    If anyone is using BeautifulSoup to parse a website and then using pandas to create a DataFrame that you may want to add styles to, you can do something like:

    (before using this you have already; imported beautifulsoup, scraped your site and created your dataframe)

    variable_name = beautifulsoup(dataframe_name.to_html())

    list = []

    `for table in variable_name.findAll('table'):`
    
      `for tbody in variable_name.findAll('table'):`
    
        `for td in variable_name.findAll('tbody'):`
    
             `list.append(td)`
    

    list[td_index]['attribute_name'] = 'attribute_value'

    This will add your all your table data to a list and you can select any element from that list and add/update a tag attribute

    (if more efficient way please comment to help improve)

    0 讨论(0)
提交回复
热议问题