简体   繁体   中英

How do I automatically wrap text inside LaTeX tables produced by pandas.to_latex()?

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)

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 eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM