简体   繁体   中英

Pandas DataFrame to Latex Formatter Functions

I am trying to export a DataFrame to Latex using a formatter function to specify the format of the columns. So far I use a function which can be used to specify the format of each column. I have the following code snippet which works fine.

def use_f_2(x):
    return "%.2f" % x

df.to_latex(formatters=[None, use_f_2, use_f_2])

This rounds the values in columns 2 and 3 to the second decimal place. Now I would like to extend this function to additionally keep the number of decimal places flexible (which is fixed to 2 in the above scenario). I would imagine it to be something like this

def use_f_2(x, num_decimals):
    return f"%.{num_decimals}f" % x

However this function cannot be used in

df.to_latex(formatters=[None, use_f_2, use_f_2])

as there are two arguments now.

Does anyone know how to implement this?

Many thanks in advance!

It's possible to use partial from functools :

import pandas as pd
import numpy as np
from functools import partial

def use_f_2(x, num_decimals):
    return f"%.{num_decimals}f" % x

# the number of columns can be passed to this function
use_f = lambda x: partial(use_f_2, num_decimals=x)

df = pd.DataFrame(np.random.rand(10, 3))
df.to_latex(formatters=[None, use_f(2), use_f(3)])

I rearranged and extended the idea of SultanOrazbayev and added the opportunity to specify the format type:

from functools import partial

# This function returns a function which formats numbers according to the specified string operations.
# Inputs
# - precision: integer -> accuracy to be shown (e.g. number of decimal places if format type is "f" or number of significant digits if format type is "g")
# - num_format: string -> format type

def format_num(precision, num_format):
    def create_formatter(num, inner_prec, inner_form):
        return "{:.{}{}}".format(num, inner_prec, inner_form)
    return partial(create_formatter, inner_prec=precision, inner_form=num_format)

Apply the function using the preferred number type and number of decimal places for each column

df.to_latex(formatters=[None, format_num(4, "g"), format_num(2, "f")])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM