将 pandas DataFrame 导出到 LaTeX 并按行应用格式化程序

Export pandas DataFrame to LaTeX and apply formatters by row

我想将一些 DataFrames 导出到 LaTeX,但这些 DataFrame 有很多列,但没有那么多项目。解决方法是显示table转置。我知道 pandas' transpose, but I want to format my rows and the method to_latex 仅支持列格式器。

一些代码:

import pandas as pd

names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]
tralala = [0.1, 0.2, 0.3, 0.4, 0.5]
BabyDataSet = zip(names,births,tralala)
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births', 'Whatever'])
df = df.transpose()
print df.to_latex()

输出:

\begin{tabular}{llllll}
\toprule
{} &    0 &        1 &     2 &     3 &    4 \
\midrule
Names    &  Bob &  Jessica &  Mary &  John &  Mel \
Births   &  968 &      155 &    77 &   578 &  973 \
Whatever &  0.1 &      0.2 &   0.3 &   0.4 &  0.5 \
\bottomrule
\end{tabular}

但是,如果我想这样做,例如:

\begin{tabular}{llllll}
\toprule
{} &    0 &        1 &     2 &     3 &    4 \
\midrule
Names    &  Bob   &  Jessica &  Mary &  John &  Mel \
Births   &  9.7e2 &    1.6e2 & 7.7e1 & 5.8e2 &  9.7e2 \
Whatever &  0.1   &      0.2 &   0.3 &   0.4 &  0.5 \
\bottomrule
\end{tabular}

有什么方法可以破解此功能吗?我唯一想到的就是在转置和导出之前手动应用将所有列转换为字符串的格式

我想到了这个:

for key in df.columns.values:
    if key in formatters:
        df[key] = df[key].apply(formatters[key])
print df.to_latex()

这几乎等同于

print df.to_latex(formatters=formatters)

并且也适用于转置数据帧,即 df.T.to_latex()