Pandas DataFrame To Latex format

Overview:

  • Latex is the format used by the Latex/Tex supported echo systems for structuring, type-setting and  publishing research documents and academic artifacts.

  • Through the to_latex() method of the DataFrame class, a pandas DataFrame can be converted into various table structures of Latex.

Example:

# Example Python program that converts a pandas DataFrame
# into a latex tabular

import pandas as pds

colorAttributes     = ("name", "rgb", "date"); 
colors              = (("salmon", "#FA8072", (250, 128,114)),
                       ("olive", "#808000", (128, 128, 0)),
                       ("teal", "#008080",    (0, 128, 128)),
                       ("thistle", "#D8BFD8", (216, 191, 216)));

colorFrame  = pds.DataFrame(data=colors);  
colorFrame.columns = colorAttributes;

print("pandas DataFrame:");
print(colorFrame);                       

# Export in latex format
latexForm = colorFrame.to_latex();

print("Latex format:");
print(latexForm);

Output:

pandas DataFrame:

      name      rgb             date

0   salmon  #FA8072  (250, 128, 114)

1    olive  #808000    (128, 128, 0)

2     teal  #008080    (0, 128, 128)

3  thistle  #D8BFD8  (216, 191, 216)

Latex format:

\begin{tabular}{llll}

\toprule

{} &     name &      rgb &             date \\

\midrule

0 &   salmon &  \#FA8072 &  (250, 128, 114) \\

1 &    olive &  \#808000 &    (128, 128, 0) \\

2 &     teal &  \#008080 &    (0, 128, 128) \\

3 &  thistle &  \#D8BFD8 &  (216, 191, 216) \\

\bottomrule

\end{tabular}

 


Copyright 2024 © pythontic.com