Search code examples
pandaslatex

python pandas: how to format big numbers in powers of ten in latex


I'm using pandas to generate some large LaTex tables with big/small numbers:

df = pd.DataFrame(np.array(outfile),columns=['Halo','$r_{v}$','etc'])
df.to_latex("uvFlux_table_{:.1f}.tex".format(z))

where "outfile" is just a table of numbers (3 columns)... How can I get the numbers in outfile to be formated like:

$1.5x10^{12}$  &   $1.5x10^{12}$  &  $1.5x10^{-12}$

-- like you'd see in a scientific publication... vs the default

0.15e13 & 0.15e13 & 0.15e-11

??


Solution

  • Defining

    def format_tex(float_number):
        exponent = np.floor(np.log10(float_number))
        mantissa = float_number/10**exponent
        mantissa_format = str(mantissa)[0:3]
        return "${0}\times10^{{{1}}}$"\
               .format(mantissa_format, str(int(exponent)))
    

    you can applymap that function on a dataframe (and apply on a series)

    df = pd.DataFrame({'col':[12345.1200000,100000000]})
    df.applymap(lambda x:format_tex(x))
    

    This gives already tex output in jupyter notebooks. Note that escaping may be tricky here. Other, faster solutions here?