diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index a269580bc4453..3b33eba2b3f89 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -1,3 +1,4 @@ + .. _whatsnew_120: What's new in 1.2.0 (??) @@ -435,6 +436,18 @@ ExtensionArray - Fixed bug where ``astype()`` with equal dtype and ``copy=False`` would return a new object (:issue:`284881`) - +ToLatex +^^^^^^^ + +- Can now substitute simple fstrings in place of callable functions in to_latex + +.. ipython:: python + + data = [[1, 2, 3], [4, 5, 6], [7, 8, 9.001]] + df = pd.DataFrame(data, columns=["a", "b", "c"], + index=["foo", "bar", "foobar"]) + result = df.to_latex(formatters=["d", ".2f", lambda x: f"{x:.3f}"]) + Other ^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 04e1fc91c5fd4..38d82ae5090fb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3017,7 +3017,7 @@ def to_latex( Write row names (index). na_rep : str, default 'NaN' Missing data representation. - formatters : list of functions or dict of {{str: function}}, optional + formatters : list of functions/str or dict of {{str: function}}, optional Formatter functions to apply to columns' elements by position or name. The result of each function must be a unicode string. List must be of length equal to the number of columns. @@ -3112,6 +3112,22 @@ def to_latex( if multirow is None: multirow = config.get_option("display.latex.multirow") + if is_list_like(formatters) and not isinstance(formatters, dict): + formatter_elems_type = all( + isinstance(elem, str) or callable(elem) for elem in formatters + ) + if formatter_elems_type: + formatters = [ + (lambda style: lambda x: "{0:{1}}".format(x, style))(style) + if isinstance(style, str) + else style + for style in formatters + ] + else: + raise ValueError( + "Formatters elements should be f-strings or callable functions" + ) + formatter = DataFrameFormatter( self, columns=columns, diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index d3d865158309c..6a5997bf0098b 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -174,6 +174,24 @@ def test_to_latex_midrule_location(self): ) assert result == expected + def test_to_latex_with_float_format_list(self): + # GH: 26278 + data = [[1, 2, 3], [4, 5, 6], [7, 8, 9.001]] + df = DataFrame(data, columns=["a", "b", "c"], index=["foo", "bar", "foobar"]) + + result = df.to_latex(formatters=["d", ".2f", lambda x: f"{x:.3f}"]) + expected = r"""\begin{tabular}{lrrr} +\toprule +{} & a & b & c \\ +\midrule +foo & 1 & 2.00 & 3.000 \\ +bar & 4 & 5.00 & 6.000 \\ +foobar & 7 & 8.00 & 9.001 \\ +\bottomrule +\end{tabular} +""" + assert result == expected + class TestToLatexLongtable: def test_to_latex_empty_longtable(self):