Back to TILs.

Calmcode TIL

Pandas to Latex logoPandas to Latex

If you're studying to be an academic, odds are that you'll need to write your thesis in latex. And if you're writing your thesis in latex, odds are that you'll need to share experiment results in a table.

It can be very tedious to do manually, but thankfully you can use pandas to automatically generate the latex for you!

import pandas as pd

df = pd.read_csv("https://calmcode.io/datasets/stocks.csv")

print(df.head(10).to_latex(index=False))

This generates the following output.

\begin{tabular}{lrrrr}
\toprule
      Date &  MSFT &  KLM &   ING &   MOS \\
\midrule
2000-01-20 & 34.35 & 0.35 & 14.06 & 14.09 \\
2000-01-21 & 34.33 & 0.35 & 13.92 & 13.79 \\
2000-01-24 & 33.30 & 0.35 & 13.56 & 13.79 \\
2000-01-25 & 32.40 & 0.35 & 13.22 & 13.45 \\
2000-01-26 & 32.86 & 0.35 & 13.33 & 13.59 \\
2000-01-27 & 32.05 & 0.35 & 13.28 & 13.25 \\
2000-01-28 & 31.48 & 0.35 & 13.09 & 13.00 \\
2000-01-31 & 31.32 & 0.35 & 12.79 & 13.30 \\
2000-02-01 & 31.60 & 0.35 & 12.78 & 13.59 \\
2000-02-02 & 32.86 & 0.35 & 12.70 & 13.45 \\
\bottomrule
\end{tabular}

If you've savvy with Latex, you can even expand the syntax by leveraging styles.

print(df
  .head(10)
  .style
  .set_properties(
     **{"Huge": "--latex--rwrap"}
  ).to_latex()
)

This decorates the table with the Huge style.

\begin{tabular}{llrrrr}
 & Date & MSFT & KLM & ING & MOS \\
0 & \Huge{2000-01-20} & \Huge{34.350000} & \Huge{0.350000} & \Huge{14.060000} & \Huge{14.090000} \\
1 & \Huge{2000-01-21} & \Huge{34.330000} & \Huge{0.350000} & \Huge{13.920000} & \Huge{13.790000} \\
2 & \Huge{2000-01-24} & \Huge{33.300000} & \Huge{0.350000} & \Huge{13.560000} & \Huge{13.790000} \\
3 & \Huge{2000-01-25} & \Huge{32.400000} & \Huge{0.350000} & \Huge{13.220000} & \Huge{13.450000} \\
4 & \Huge{2000-01-26} & \Huge{32.860000} & \Huge{0.350000} & \Huge{13.330000} & \Huge{13.590000} \\
5 & \Huge{2000-01-27} & \Huge{32.050000} & \Huge{0.350000} & \Huge{13.280000} & \Huge{13.250000} \\
6 & \Huge{2000-01-28} & \Huge{31.480000} & \Huge{0.350000} & \Huge{13.090000} & \Huge{13.000000} \\
7 & \Huge{2000-01-31} & \Huge{31.320000} & \Huge{0.350000} & \Huge{12.790000} & \Huge{13.300000} \\
8 & \Huge{2000-02-01} & \Huge{31.600000} & \Huge{0.350000} & \Huge{12.780000} & \Huge{13.590000} \\
9 & \Huge{2000-02-02} & \Huge{32.860000} & \Huge{0.350000} & \Huge{12.700000} & \Huge{13.450000} \\
\end{tabular}

You can even go a step further and translate some css in.

print(df
  .head(10)
  .style
  .set_properties(
     **{"font-weight": "bold", "Huge": "--latex--rwrap"}
  ).to_latex(convert_css=True)
)

Back to main.