Code Sample
import pandas as pd
df = pd.DataFrame([[0.19999]])
print(df.to_latex(float_format='%.3f'))
# returns:
# \begin{tabular}{lr}
# \toprule
# {} & 0 \\
# \midrule
# 0 & 0.2 \\
# \bottomrule
# \end{tabular}
Problem description
The float format doesn't seem to be respected in the example above. In contrast:
'%.3f' % df.values[0][0]
# returns
# '0.200'
I would expect the number to be rendered as 0.200
instead of 0.2
.
Issue #6052 is possibly related, but the problem description is different.
Expected Output
\begin{tabular}{lr}
\toprule
{} & 0 \\
\midrule
0 & 0.200 \\
\bottomrule
\end{tabular}
Output of pd.show_versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.5.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-128-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8
pandas: 0.23.1
pytest: None
pip: 10.0.1
setuptools: 39.2.0
Cython: None
numpy: 1.14.5
scipy: None
pyarrow: None
xarray: None
IPython: 6.4.0
sphinx: None
patsy: None
dateutil: 2.7.3
pytz: 2018.4
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
Comment From: WillAyd
Thanks for the report - investigation and PRs are always welcome!
Comment From: tomneep
float_format
takes a function rather than a string so if you do:
import pandas as pd
df = pd.DataFrame([[0.19999]])
print(df.to_latex(float_format=lambda x: '%.3f' % x))
you'll get what you want. It isn't just to_latex
that is affected by this, to_string
and to_html
have the same behaviour. One problem is that the to_latex
docstring isn't inheriting the docstring from to_string
(which it probably should), so this information is hidden away.
to_csv
on the otherhand, does seem to accept a string, according to the docstring.
Comment From: fzalkow
Oops, I wasn't aware it is expecting a function! Thanks a lot, this way it works! From my perspective, issue can be closed... Thanks again!
Comment From: WillAyd
float_format
accepts a string for the other to_...
functions and it should here, so this is still a bug if anyone wants to work it
Comment From: tomneep
I think the problem is that trailing zeros are being "trimmed" away. Presuming float_format
should override this behaviour then a potential fix is 79b5acb5929333f0d0cd602b5ac206b29cc589a6. If that sounds like the right logic then I'll open a PR (when time permits).
Comment From: Dr-Left
It is fine with a function, however the official document still tells me to pass a string to float_format argument... Anyone can fix it, or to change the document is fine as well because now it is misleading