Python 从 Pandas DataFrame 导出 LaTeX 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14380371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:14:51  来源:igfitidea点击:

Export a LaTeX table from pandas DataFrame

pythonlatexdataframepandas

提问by PlagTag

Is there an easy way to export a data frame (or even a part of it) to LaTeX?

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

I searched in google and was only able to find solutions using asciitables.

我在谷歌搜索,只能找到使用 asciitables 的解决方案。

采纳答案by bmu

DataFrames have a to_latex(see the pandas docs) method:

DataFrames 有一个to_latex(参见pandas 文档)方法:

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}

You can simply write this to a tex file.

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

By default latex will render this as:

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

as it would appear in latex

因为它会出现在乳胶中

Note: the to_latex(see the pandas docs) method offers several configuration options.

注意:(to_latex参见pandas 文档)方法提供了几个配置选项。

回答by Thorsten Kranz

Just write to a textfile. It's no magic:

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

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}")

回答by Armin Alibasic

If you want to save it:

如果你想保存它:

with open('mytable.tex', 'w') as tf:
     tf.write(df.to_latex())