Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you control float formatting when using DataFrame.to_markdown in pandas?

I'm trying to use DataFrame.to_markdown with a dataframe that contains float values that I'd like to have rounded off. Without to_markdown() I can just set pd.options.display.float_format and everything works fine, but to_markdown doesn't seem to be respecting that option.

Repro:

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [42.42, 99.11234123412341234, -23]])
pd.options.display.float_format = '{:,.0f}'.format
print(df)
print()
print(df.to_markdown())

outputs:

   0  1   2
0  1  2   3
1 42 99 -23

|    |     0 |       1 |   2 |
|---:|------:|--------:|----:|
|  0 |  1    |  2      |   3 |
|  1 | 42.42 | 99.1123 | -23 |

(compare the 42.42 and 99.1123 in the to_markdown table to the 42 and 99 in the plain old df)

Is this a bug or am I missing something about how to use to_markdown?

like image 436
mgalgs Avatar asked Jun 19 '26 02:06

mgalgs


1 Answers

It looks like pandas uses tabulate for this formatting. If it's installed, you can use something like:

df.to_markdown(floatfmt=".0f")

output:

|    |   0 |   1 |   2 |
|---:|----:|----:|----:|
|  0 |   1 |   2 |   3 |
|  1 |  42 |  99 | -23 |
like image 59
anon01 Avatar answered Jun 21 '26 17:06

anon01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!