jupyter笔记本数据框显示对齐数字

时间:2017-02-10 19:10:22

标签: pandas jupyter-notebook

当在Jupyter笔记本中显示pandas数据框时,所有单元格都保持对齐。是否可以右对齐数字列?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用Style。很漂亮:)

df = pd.DataFrame ( 
    [ (1,) * 3, (100,) *3, (1000,)* 3 ], 
    columns="first second third".split() 
)

def column_styler (col):
    if col.name == "first":
        align = "left"
    elif col.name == "third":
        align = "right"
    else:
        align = "center"

    return [ "text-align: %s" % align ] * len(col)

df.style.apply (column_styler)

Aligned results