How can I format IPython html display of pandas dataframes so that
- numbers are right justified
- numbers have commas as thousands separator
- large floats have no decimal places
I understand that numpy
has the facility of set_printoptions
where I can do:
int_frmt:lambda x : '{:,}'.format(x)
np.set_printoptions(formatter={'int_kind':int_frmt})
and similarly for other data types.
But IPython does not pick up these formatting options when displaying dataframes in html. I still need to have
pd.set_option('display.notebook_repr_html', True)
but with 1, 2, 3 as in above.
Edit: Below is my solution for 2 & 3 ( not sure this is the best way ), but I still need to figure out how to make number columns right justified.
from IPython.display import HTML
int_frmt = lambda x: '{:,}'.format(x)
float_frmt = lambda x: '{:,.0f}'.format(x) if x > 1e3 else '{:,.2f}'.format(x)
frmt_map = {np.dtype('int64'):int_frmt, np.dtype('float64'):float_frmt}
frmt = {col:frmt_map[df.dtypes[col]] for col in df.columns if df.dtypes[col] in frmt_map.keys()}
HTML(df.to_html(formatters=frmt))
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…