When a pandas data frame is displayed in Jupyter notebook, all cells are left aligned. Is it possible to right-align numeric columns?
Asked
Active
Viewed 1,565 times
2 Answers
1
You can use Style. It's beautiful :)
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)

caxcaxcoatl
- 8,472
- 1
- 13
- 21
0
Consider the dataframe df
df = pd.DataFrame(dict(
A_______=[1, 2],
B_______=list('xy'),
C_______=[3, 4],
))
df
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)
Custom 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>
Result
HTML_with_style(df, style)

Community
- 1
- 1

piRSquared
- 285,575
- 57
- 475
- 624