Skip to content

BUG: Respect na_rep in DataFrame.to_latex() when used with formatters (#9046) #25799

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ I/O
- Improved performance in :meth:`pandas.read_stata` and :class:`pandas.io.stata.StataReader` when converting columns that have missing values (:issue:`25772`)
- Bug in :func:`read_hdf` not properly closing store after a ``KeyError`` is raised (:issue:`25766`)
- Bug in ``read_csv`` which would not raise ``ValueError`` if a column index in ``usecols`` was out of bounds (:issue:`25623`)
- Bug in :meth:`DataFrame.to_latex` that would ignore ``na_rep`` if the ``formatters`` argument was used (:issue:`9046`)
-


Plotting
^^^^^^^^
Expand Down
8 changes: 6 additions & 2 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1063,7 +1063,10 @@ def get_result_as_array(self):
"""

if self.formatter is not None:
return np.array([self.formatter(x) for x in self.values])
out = np.array([self.formatter(x) for x in self.values])
mask = isna(self.values)
out[mask] = self.na_rep
return out

if self.fixed_width:
threshold = get_option("display.chop_threshold")
Expand Down Expand Up @@ -1142,7 +1145,8 @@ def format_values_with(float_format):
def _format_strings(self):
# shortcut
if self.formatter is not None:
return [self.formatter(x) for x in self.values]
return [self.formatter(x) if not isna(x) else self.na_rep
for x in self.values]

return list(self.get_result_as_array())

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/io/formats/test_to_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,5 +741,22 @@ def test_to_latex_multindex_header(self):
0 & 1 & 2 & 3 \\
\bottomrule
\end{tabular}
"""
assert observed == expected

def test_to_latex_na_rep_formatters(self):
# GH 9046
df = pd.DataFrame({'a': [0, 1, 2], 'b': [0.1, None, 0.2]})
observed = df.to_latex(
formatters={'b': '{:0.4f}'.format}, na_rep='-')
expected = r"""\begin{tabular}{lrr}
\toprule
{} & a & b \\
\midrule
0 & 0 & 0.1000 \\
1 & 1 & - \\
2 & 2 & 0.2000 \\
\bottomrule
\end{tabular}
"""
assert observed == expected