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

Pandas jupyter笔记本电脑数据框显示数字对齐,pandas,jupyter-notebook,Pandas,Jupyter Notebook,当熊猫数据框显示在Jupyter笔记本中时,所有单元格均左对齐。可以右对齐数字列吗?考虑数据框df df = pd.DataFrame(dict( A_______=[1, 2], B_______=list('xy'), C_______=[3, 4], )) df 您可以使用。很美:) def HTML_with_style(df, style=None, random_id=None): from IPython.di

当熊猫数据框显示在Jupyter笔记本中时,所有单元格均左对齐。可以右对齐数字列吗?

考虑数据框
df

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

    ))
df

您可以使用。很美:)

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)
# 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)
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)