70

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

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

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
PlagTag
  • 6,107
  • 6
  • 36
  • 48
  • In addition to the replies here, this question has an interesting approach too. Export to csv and then import the csv into latex: http://tex.stackexchange.com/questions/54990/convert-numpy-array-into-tabular – Ricardo Magalhães Cruz Nov 03 '15 at 14:17

3 Answers3

107

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

>>> df = pd.DataFrame(np.random.random((5, 5)))
>>> df  
          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

>>> 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.

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.

iacob
  • 20,084
  • 6
  • 92
  • 119
bmu
  • 35,119
  • 13
  • 91
  • 108
10

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}")
Thorsten Kranz
  • 12,492
  • 2
  • 39
  • 56
  • 10
    Although it is useful to show how easy it is to export tabular data to LaTeX using plain Python, it is of course much better to use existing facilities, i.e., `DataFrame.to_latex()` in this case. – hans_meine Mar 12 '14 at 10:49
  • 6
    Hi, I totally agree. My reasons were: 1. I started with pandas before version 0.9, where to_latex wasn't available 2. This might be useful when some adjustement is needed or someone wants to export to another format, e.g., XAML, custom XML or whatever. But thank you for your comment – Thorsten Kranz Mar 12 '14 at 12:55
10

If you want to save it:

with open('mytable.tex', 'w') as tf:
     tf.write(df.to_latex())
Armin Alibasic
  • 261
  • 4
  • 9