Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas styler does not maintain rounding

I would like to round off Pandas DataFrame and then add a title to it, but Pandas style.set_caption command ruins the rounding.

example:

pd.DataFrame(np.array([[0.555,0.444],[0.333,0.222]])).round(decimals = 2).style.set_caption("hello")

result:

hello
    0   1
0   0.560000    0.440000
1   0.330000    0.220000

How can I add a title while maintaing rouding?

like image 452
user67275 Avatar asked Sep 19 '25 23:09

user67275


1 Answers

The answer is Styler.format. For example:

df = pd.DataFrame(np.array([[0.555,0.444],[0.333,0.222]]))
df.style.set_caption("hello").format('{:.2f}')

For Pandas 1.3.0+, you can just pass precision=2:

df.style.set_caption("hello").format(precision=2)

Output:

enter image description here

like image 71
Quang Hoang Avatar answered Sep 22 '25 13:09

Quang Hoang