tigio_33
tigio_33

Reputation: 149

Formatting code to_latex from Python Pandas

I am trying to translate a dataframe I created on pandas to a LatEx file on Overleaf. To do so I retrieved the applicable code from Python using the following code:

print(macro_df.to_latex())

And I received the following output:

\begin{tabular}{lr}
\toprule
{} &      0 \\
macro\_ind                         &        \\
\midrule
Agriculture, forestry and fishing &    293 \\
Construction                      &    947 \\
Manufacturing                     &  36425 \\
Mining                            &   4239 \\
Retail Trade                      &   4594 \\
Services                          &  14221 \\
Transportation                    &   5187 \\
Wholesale trade                   &   2310 \\
\bottomrule
\end{tabular}

Once I copy paste in the Overleaf prompt, the values and text are perfectly fine, the only problem is that the table is too thin. I would like to choose manually the width that the table occupies in the page, and I have been unable to do so. I have tried with tabularx and tabular* packages, but they are not usable on Overleaf (for some reason - maybe I am doing something wrong?) so I am using tabular. I have also tried to format the column width \begin{tabular}{l{8cm}r{2m}}, but it doesn't seem to work.

Can somebody help me out, cause I spend hours trying and trying!

Thank you in advance for your help :)

Any other viable solution of moving the table from pandas to latex will also be welcomed!

Upvotes: 0

Views: 530

Answers (2)

gimlet
gimlet

Reputation: 11

You could define your own column type like this:

\newcolumntype{L}{>{\raggedright\arraybackslash}X}

\begin{table}[!h]

\begin{tabularx}{\textwidth}{L{nncm}L{nncm}
blah & blah \\
\end{tabularx}

\end{table}

This will wordwrap nicely too. nn is how large you want the column or leave it blank and let the textwidth handle it for you

Upvotes: 1

Kian Mirjalali
Kian Mirjalali

Reputation: 62

Did you try \hspace as a workaround? Something like this:

...
\toprule
‎\hspace{10cm}‎ &      0 \\
...

Upvotes: 1

Related Questions