Write a program in Python to convert a given dataframe to a LaTex document

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for converted to latex as,

\begin{tabular}{lrr}
\toprule
{} &   Id &  Age \\
\midrule
0 &    1 &    12 \\
1 &    2 &    13 \\
2 &    3 &    14 \\
3 &    4 &    15 \\
4 &    5 &    16 \\
\bottomrule
\end{tabular}

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Apply to_latex() function to the dataframe and set index and multirow values as True. It is defined below,

df.to_latex(index = True, multirow = True)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id': [1,2,3,4,5],
                     'Age': [12,13,14,15,16]})
print(df.to_latex(index = True, multirow = True))

Output

\begin{tabular}{lrr}
\toprule
{} &   Id &  Age \\
\midrule
0 &    1 &    12 \\
1 &    2 &    13 \\
2 &    3 &    14 \\
3 &    4 &    15 \\
4 &    5 &    16 \\
\bottomrule
\end{tabular}
raja
Published on 12-Feb-2021 11:13:04
Advertisements