[ad_1]
I am using a pandas dataframe to store ufloats from the uncertainties library (https://pythonhosted.org/uncertainties/). I am having difficulties outputing the table in a LaTeX format. Some methods I have tried are below (this question doesn’t help: LaTeX Table with uncertainty from pandas Dataframe). Any suggestions?
import pandas as pd
from uncertainties import ufloat
df = pd.DataFrame([{'Sample': 'quartz', 'Age': ufloat(43.98, 0.12), 'Mass': ufloat(62.87, 1.87)}, {'Sample': 'sapphire', 'Age': ufloat(33.98, 2.20), 'Mass': ufloat(6.87, 2.87)}])
df = df.set_index('Sample') # To index by sample
#Simple print not good
print(df, "\n")
# Age Mass
# Sample
# quartz 43.98+/-0.12 62.9+/-1.9
# sapphire 34.0+/-2.2 6.9+/-2.9
# Basic to_latex doesn't include $, doesn't convert +:- to \pm
print(df.to_latex(), "\n")
# \begin{tabular}{lll}
# \toprule
# {} & Age & Mass \\
# Sample & & \\
# \midrule
# quartz & 43.98+/-0.12 & 62.9+/-1.9 \\
# sapphire & 34.0+/-2.2 & 6.9+/-2.9 \\
# \bottomrule
# \end{tabular}
# Formatter of uncertainties library works by itself...
def fmtFc(x): return '${:L}'.format(x) + '$'
print(fmtFc(ufloat(65.98, 0.96)), "\n")
# $66.0 \pm 1.0$
# ... but gets mangled by dataframe
print(df.to_latex(formatters=[fmtFc]*len(df.columns)))
# \begin{tabular}{lll}
# \toprule
# {} & Age & Mass \\
# Sample & & \\
# \midrule
# quartz & 43.98 \textbackslash pm 0.12 & 62.9 \textbackslash pm 1.9 \\
# sapphire & 34.0 \textbackslash pm 2.2 & 6.9 \textbackslash pm 2.9 \\
# \bottomrule
# \end{tabular}
# The output I would like
# \begin{tabular}{lll}
# \toprule
# {} & Age & Mass \\
# Sample & & \\
# \midrule
# quartz & $43.98 \pm 0.12$ & $62.9 \pm 1.9$ \\
# sapphire & $34.0 \pm 2.2$ & $6.9 \pm 2.9$ \\
# \bottomrule
# \end{tabular}
[ad_2]