Reputation: 231
I am using pandas.DataFrame.to_latex()
to automatically turn a text-filled pd.DataFrame
into a LaTeX
table. Everything seems fine but if the text is long, it is not broken. Using
longtable = True
does not help. Here are my settings
df.to_latex(multicolumn = True, header = True, index_names = False,
index = False, longtable = True)
Upvotes: 3
Views: 7033
Reputation: 3711
In LaTeX tables you control the column formats of a table with the {table spec}
argument like this
\begin{tabular}[pos]{table spec}
The pandas.DataFrame.to_latex()
can pass a format string to this argument with the column_format
parameter. If you want to have fixed with of two columns, use e.g.
column_format='p{3.5cm}|p{5cm}'
Here is a short example illustrating how to utilize this to fix a problem comparable to yours:
import pandas as pd
import string
# Creating mock data
data_lower = string.ascii_lowercase
data_lower = ' '.join(data_lower[i:i+3] for i in range(0, len(data_lower), 3))
# >>> abc def ghi jkl mno pqr stu vwx yz
data_upper = string.ascii_uppercase
data_upper = ' '.join(data_upper[i:i+3] for i in range(0, len(data_upper), 3))
# >>> ABC DEF GHI JKL MNO PQR STU VWX YZ
df = pd.DataFrame({'this is a long entry in the table in minuscules':
data_lower,
'THIS IS A LONG ENTRY IN THE TABLE IN MAJUSCULES':
data_upper}, index=[0])
df.to_latex(multicolumn=True, header=True, index_names=False,
index=False, column_format='p{3.5cm}|p{5cm}')
This gives
\begin{tabular}{p{3.5cm}|p{5cm}}
\toprule
this is a long entry in the table in minuscules & THIS IS A LONG ENTRY IN THE TABLE IN MAJUSCULES \\
\midrule
abc def ghi jkl mno pqr stu vwx yz & ABC DEF GHI JKL MNO PQR STU VWX YZ \\
\bottomrule
\end{tabular}
and breaks the lines in the table at 3.5cm and 5cm respectively
if you remove the column_format='p{3.5cm}|p{5cm}'
parameter you'll end up in too long cell entries of the latex table, what I believe is your problem.
Upvotes: 2