Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k 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 (41.4k 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'))

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 30, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...