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

Export pandas DataFrame to LaTeX and apply formatters by row

我想将某些DataFrame导出到LaTeX,但是这些DataFrame具有很多列,但是没有那么多项目。解决方案是显示转置的表。我知道pandas的转置,但是我想格式化行,并且to_latex方法仅按列支持格式化程序。

某些代码:

1
2
3
4
5
6
7
8
9
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()

输出:

1
2
3
4
5
6
7
8
9
\\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}

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

1
2
3
4
5
6
7
8
9
\\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}

有什么办法可以破解此功能?我唯一想到的就是在转置和导出

之前手动应用将所有列转换为字符串的格式


我想到了这个:

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

这几乎等同于

1
print df.to_latex(formatters=formatters)

并与转置的DataFrames一起使用,即df.T.to_latex()