0 votes
1 view
in Data Science by (14.9k points)

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

1 Answer

0 votes
by (23.5k points)

HTML receives a custom string of html data. Nobody forbids you to pass in a style tag with the custom CSS style for the .dataframe class (which the to_html method adds to the table).

So the simplest solution would be to just add a style and concatenate it with the output of the df.to_html:

style = '<style>.dataframe td { text-align: right; }</style>'

HTML( style + df.to_html( formatters=frmt ) )

But I would suggest to define a custom class for a DataFrame since this will change the style of all the tables in your notebook (style is "global").

style = '<style>.right_aligned_df td { text-align: right; }</style>'

HTML(style + df.to_html(formatters=frmt, classes='right_aligned_df'))

You can also define the style in one of the previous cells, and then just set the classes parameter of the to_html method:

# Some cell at the begining of the notebook

In [2]: HTML('''<style>

                    .right_aligned_df td { text-align: right; }

                    .left_aligned_df td { text-align: right; }

                    .pink_df { background-color: pink; }

                </style>''')

...

# Much later in your notebook

In [66]: HTML(df.to_html(classes='pink_df'))

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...