Pandas df.style.bar while maintaining rounding

Viewed 2455

When I apply the bar styling to a pandas dataframe after rounding I lose the rounding formatting, and I can't figure out how to apply the rounding formatting after because df.style.bar doesn't return a dataframe but a "Styler" object.

df = pd.DataFrame({'A': [1.23456, 2.34567,3.45678],  'B':[2,3,4]})
df['A'] = df['A'].round(2)
df.style.bar(subset='A')

This returns

enter image description here

but I don't want all of those extra zeros displayed.

1 Answers

You will have to treat a styler as purely a rendering of the original dataframe. This means you can use a format to display the data rounded to 2 decimal places.

The basic idea behind styling is that a user will want to modify the way the data is presented but still preserve the underlying format for further manipulation.

f = {'A':'{:.2f}'} #column col A to 2 decimals
df.style.format(f).bar(subset='A')

enter image description here

Read this excellent tutorial for exploring what all you can do with it and how.

EDIT: Added a formatting dict to show general use and to only apply the format to a single column.

Related