python-从pandas DataFrame导出LaTeX表

是否有一种简单的方法可以将数据帧(甚至其中的一部分)导出到LaTeX?

我在Google中搜索,仅能使用asciitables找到解决方案。

PlagTag asked 2020-08-08T22:15:05Z
3个解决方案
74 votes

数据框具有to_latex方法:

In [42]: df = pd.DataFrame(np.random.random((5, 5)))

In [43]: df
Out[43]: 
          0         1         2         3         4
0  0.886864  0.518538  0.359964  0.167291  0.940414
1  0.834130  0.022920  0.265131  0.059002  0.530584
2  0.648019  0.953043  0.263551  0.595798  0.153969
3  0.207003  0.015721  0.931170  0.045044  0.432870
4  0.039886  0.898780  0.728195  0.112069  0.468485

In [44]: print df.to_latex()
\begin{tabular}{|l|c|c|c|c|c|c|}
\hline
{} &         0 &         1 &         2 &         3 &         4 \\
\hline
0 &  0.886864 &  0.518538 &  0.359964 &  0.167291 &  0.940414 \\
1 &  0.834130 &  0.022920 &  0.265131 &  0.059002 &  0.530584 \\
2 &  0.648019 &  0.953043 &  0.263551 &  0.595798 &  0.153969 \\
3 &  0.207003 &  0.015721 &  0.931170 &  0.045044 &  0.432870 \\
4 &  0.039886 &  0.898780 &  0.728195 &  0.112069 &  0.468485 \\
\hline
\end{tabular}

您可以简单地将其写入tex文件。

默认情况下,乳胶将其呈现为:

as it would appear in latex

注意:to_latex方法提供了几种配置选项。

bmu answered 2020-08-08T22:15:23Z
6 votes

只需写入文本文件即可。 这不是魔术:

import pandas as pd
df = pd.DataFrame({"a":range(10), "b":range(10,20)})
with open("my_table.tex", "w") as f:
    f.write("\\begin{tabular}{" + " | ".join(["c"] * len(df.columns)) + "}\n")
    for i, row in df.iterrows():
        f.write(" & ".join([str(x) for x in row.values]) + " \\\\\n")
    f.write("\\end{tabular}")
Thorsten Kranz answered 2020-08-08T22:15:43Z
5 votes

如果要保存:

with open('mytable.tex', 'w') as tf:
     tf.write(df.to_latex())
Armin Alibasic answered 2020-08-08T22:16:03Z
translate from https://stackoverflow.com:/questions/14380371/export-a-latex-table-from-pandas-dataframe