Change the color of text within a pandas dataframe html table python using styles and css

前端 未结 2 1462
旧时难觅i
旧时难觅i 2020-11-27 06:19

I have a pandas dataframe:

arrays = [[\'Midland\', \'Midland\', \'Hereford\', \'Hereford\', \'Hobbs\',\'Hobbs\', \'Childress\',
           \'Childress\', \'R         


        
2条回答
  •  星月不相逢
    2020-11-27 06:33

    This takes a few steps:

    First import HTML and re

    from IPython.display import HTML
    import re
    

    You can get at the html pandas puts out via the to_html method.

    df_html = df.to_html()
    

    Next we are going to generate a random identifier for the html table and style we are going to create.

    random_id = 'id%d' % np.random.choice(np.arange(1000000))
    

    Because we are going to insert some style, we need to be careful to specify that this style will only be for our table. Now let's insert this into the df_html

    df_html = re.sub(r'

    And create a style tag. This is really up to you. I just added some hover effect.

    style = """
    
    """.format(random_id=random_id)
    

    Finally, display it

    HTML(style + df_html)
    

    Function all in one.

    def HTML_with_style(df, style=None, random_id=None):
        from IPython.display import HTML
        import numpy as np
        import re
    
        df_html = df.to_html()
    
        if random_id is None:
            random_id = 'id%d' % np.random.choice(np.arange(1000000))
    
        if style is None:
            style = """
            
            """.format(random_id=random_id)
        else:
            new_style = []
            s = re.sub(r'', '', style).strip()
            for line in s.split('\n'):
                    line = line.strip()
                    if not re.match(r'^table', line):
                        line = re.sub(r'^', 'table ', line)
                    new_style.append(line)
            new_style = ['']
    
            style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))
    
        df_html = re.sub(r'

    Use it like this:

    HTML_with_style(df.head())
    

    HTML_with_style(df.head(), '')
    

    style = """
    
    """
    HTML_with_style(df.head(), style)
    

    Learn CSS and go nuts!

提交回复
热议问题