2017-02-10 60 views

回答

0

考虑数据框df

df = pd.DataFrame(dict(
     A_______=[1, 2], 
     B_______=list('xy'), 
     C_______=[3, 4], 

    )) 
df 

enter image description here

Use function from Useful Answer Here

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 = """ 
     <style> 
      table#{random_id} {{color: blue}} 
     </style> 
     """.format(random_id=random_id) 
    else: 
     new_style = [] 
     s = re.sub(r'</?style>', '', 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>'] + new_style + ['</style>'] 

     style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style)) 

    df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html) 

    return HTML(style + df_html) 

自定义CSS

# grab ordinal positions of numeric columns 
pos = [df.columns.get_loc(c) for c in df.select_dtypes([np.number]).columns] 

# number of index levels. need to account for this in css nth-child calc 
n = df.index.nlevels 

cell_style = 'text-align: right' 
nth_style = 'table tr td:nth-child({}) {{{}}}' 
style_tag = '<style>\n{}\n</style>' 
style = style_tag.format(
    '\n'.join([nth_style.format(i + n + 1, cell_style) for i in pos])) 

print(style) 

<style> 
table tr td:nth-child(2) {text-align: right} 
table tr td:nth-child(4) {text-align: right} 
</style> 

结果

HTML_with_style(df, style) 

enter image description here