Pandas df.to_latex() output gets truncated

Viewed 1152

Problem: I tried to export a pandas.DataFrame to LaTex using .to_latex().

However, the output for long values (in my case long strings) gets truncated.

Step to reproduce:

import pandas as pd 
df = pd.DataFrame(['veryLongString' * i for i in range(1, 5)], dtype='string')
print(df.to_latex())

Output:

\begin{tabular}{ll}
\toprule
{} &                                                  0 \\
\midrule
0 &                                     veryLongString \\
1 &                       veryLongStringveryLongString \\
2 &         veryLongStringveryLongStringveryLongString \\
3 &  veryLongStringveryLongStringveryLongStringvery... \\
\bottomrule
\end{tabular}

As you can see, the last row gets truncated (with ...). I already tried to use the col_space parameter but this does not change the behavior as expected. It simply shifts the table cells as following:

\begin{tabular}{ll}
\toprule
{} &                                                            0 \\
\midrule
0                                                  &                                     veryLongString \\
1                                                  &                       veryLongStringveryLongString \\
2                                                  &         veryLongStringveryLongStringveryLongString \\
3                                                  &  veryLongStringveryLongStringveryLongStringvery... \\
\bottomrule
\end{tabular}
 

How do I get the full content of the DataFrame exported to Latex?

2 Answers

You can call the context manager with a with statement to temporarily change the max column width:

with pd.option_context("max_colwidth", 1000):
    print (df.to_latex())

Output:

\begin{tabular}{ll}
\toprule
{} &                                                         0 \\
\midrule
0 &                                            veryLongString \\
1 &                              veryLongStringveryLongString \\
2 &                veryLongStringveryLongStringveryLongString \\
3 &  veryLongStringveryLongStringveryLongStringveryLongString \\
\bottomrule
\end{tabular}

This behaviour is also described here.

After spending some time trying out other parameters from to_latex() as well as other export options, e.g., to_csv(), I was sure that this is not a problem of to_latex().

I found the solution in the pandas documentation:

enter image description here

So the solution is setting this option to None to don't restrict the output (globally).

pd.set_option('display.max_colwidth', None)

Source: https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html

Related