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



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}
Updated on: 2021-02-25T07:20:06+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements