Transform a Pandas DataFrame to Latex table


If you ever tried to write a big table in Latex from scratch, you know how much it can be tedious. Fortunately, there are ways to convert data from a Pandas DataFrame to a Latex table with a simple call.

Making tables in Latex from Pandas DataFrames

Pandas dataframe to latex table
From Pandas to Latex seamlessly!

Latex is known as the “gold standard” for writing academic papers and books. It has extensive formatting options, a great integration with reference management tools like Bibtex, and it produces aesthetically pleasant outputs.

If you spent time more than once creating a table from scratch in Latex, you know it may be a terribly tedious process. And probably you dread going back and change that table, in case it needs to be updated.

Fortunately, other smart people had the same problem before and decided to do something about it. Amongst the large number of formats you can export data to in Pandas, you can also find Latex.

Creating your table

Let’s imagine you are handling your data in a Jupyter Notebook, and you want to export your results for inserting into your Latex document. Most probably, the object holding that data in a tabular format will be a Pandas DataFrame.

Then it’s your lucky day! All you need to do is to call one of the fantastic DataFrame methods:

import pandas as pd
df = pd.DataFrame({
    "X": [10, 5, 7], 
    "Y": [21,15,9], 
    "p": [0.631, 0.557,0.364]

The above command will return you a string with the Pandas DataFrame formatted as Latex Table and ready to be inserted in your Latex document. Specifically:

\\begin{tabular}{lrrr}\n\\toprule\n{} & X & Y & p \\\\\n\\midrule\n0 & 10 & 21 & 0.631 \\\\\n1 & 5 & 15 & 0.557 \\\\\n2 & 7 & 9 & 0.364 \\\\\n\\bottomrule\n\\end{tabular}\n

There is a long set of parameters available to you in order to fine-tune the Latex table. Here I report some of the most useful:

  • columns: the list of columns to export (by default, all of them)
  • col_space: the minimum width of each column
  • index: whether to write row names (by default True)
  • caption: string or tuple used for latex caption
  • label: string used as Latex label

I plan to write additional blog posts on this topic. More specifically, I plan to publish a small GUI program that leverages Pandas to create Latex tables from CSV files. Furthermore, I plan to create a open API and website that accepts CSV files as input and returns the code to create the corresponding Latex table.

Related links

  • Pandas DataFrame.to_latex() documentation link

Do you like our content? Check more of our posts in our blog!