2
當Jupyter筆記本顯示熊貓數據幀時,所有單元格都左對齊。是否可以正確對齊數字列?jupyter筆記本數據幀顯示對齊號碼
當Jupyter筆記本顯示熊貓數據幀時,所有單元格都左對齊。是否可以正確對齊數字列?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)