问题: Pandas.DataFrame.to_latex() 输出的表不包含长列标题。从 Pandas 0.24 开始,line_width= 参数已被删除。
讨论:
我使用 df.to_latex() 命令导出许多表,以包含在主文档中。许多表格都有冗长的列标题,主要是因为需要包含括号内的单位。
最终结果是一组极其稀疏的表格,通常无法容纳在页面上。
下面是一个过于稀疏的生成 Tex 的示例:
\begin{tabular}{lrrrrrr}
\toprule
{} & Odometer (km/y) & Fuel (L/y) & Elec (kWh/y) & Economy (L/100km) & GHG (kg CO2e) & GHG (g/km) \\
Type & & & & & & \\
\midrule
Type 1 & 70753.62 & 9721.06 & 0.00 & 13.74 & 21386.33 & 302.26 \\
Type RRR & 56167.39 & 5285.40 & 1627.60 & 9.41 & 11642.54 & 207.28 \\
Type X & 195756.35 & 42957.04 & 0.00 & 21.94 & 94505.48 & 482.77 \\
Type Huh & 187384.66 & 18118.07 & 73.07 & 9.67 & 39860.40 & 212.72 \\
\bottomrule
\end{tabular}
Run Code Online (Sandbox Code Playgroud)
问题:
\input这些表格并指定换行宽度?该问题取决于列的声明方式。当指定“r”时,您会说“为较大的单元格提供足够宽的列并右对齐”。
您需要做的是使用column_format参数以 p{width} 给出列的宽度,在这种情况下,列项将被格式化为给定宽度的段落,并根据需要换行。
例如,Pandas 命令:
df.to_latex(column_format='lp{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}')
Run Code Online (Sandbox Code Playgroud)
应该会产生一个输出 .tex 文件,看起来或多或少像这样:
\documentclass{article}
\begin{document}
\begin{tabular}{lp{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}}
\hline
{} & Odometer (km/y) & Fuel (L/y) & Elec (kWh/y) & Economy (L/100km) & GHG (kg CO2e) & GHG (g/km) \\
Type & & & & & & \\
\hline
Type 1 & 70753.62 & 9721.06 & 0.00 & 13.74 & 21386.33 & 302.26 \\
Type RRR & 56167.39 & 5285.40 & 1627.60 & 9.41 & 11642.54 & 207.28 \\
Type X & 195756.35 & 42957.04 & 0.00 & 21.94 & 94505.48 & 482.77 \\
Type Huh & 187384.66 & 18118.07 & 73.07 & 9.67 & 39860.40 & 212.72 \\
\hline
\end{tabular}
\bigskip
If you want to control line breaking, just add a $\backslash${newline} where you want.
\begin{tabular}{lp{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}}
\hline
{} & Odometer\newline (km/y) & Fuel \newline (L/y) & Elec\newline (kWh/y) & Economy\newline (L/100km) & GHG\newline (kg CO2e) & GHG\newline (g/km) \\
Type & & & & & & \\
\hline
Type 1 & 70753.62 & 9721.06 & 0.00 & 13.74 & 21386.33 & 302.26 \\
Type RRR & 56167.39 & 5285.40 & 1627.60 & 9.41 & 11642.54 & 207.28 \\
Type X & 195756.35 & 42957.04 & 0.00 & 21.94 & 94505.48 & 482.77 \\
Type Huh & 187384.66 & 18118.07 & 73.07 & 9.67 & 39860.40 & 212.72 \\
\hline
\end{tabular}
\bigskip
You can also consider adding an extra row for the units.
\begin{tabular}{lp{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}}
\hline
{} & Odometer & Fuel & Elec & Economy & GHG & GHG \\
Type & (km/y) & (L/y) & (kWh/y) & (L/100km) & (kg CO2e) & (g/km) \\
\hline
Type 1 & 70753.62 & 9721.06 & 0.00 & 13.74 & 21386.33 & 302.26 \\
Type RRR & 56167.39 & 5285.40 & 1627.60 & 9.41 & 11642.54 & 207.28 \\
Type X & 195756.35 & 42957.04 & 0.00 & 21.94 & 94505.48 & 482.77 \\
Type Huh & 187384.66 & 18118.07 & 73.07 & 9.67 & 39860.40 & 212.72 \\
\hline
\end{tabular}
\end{document}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3579 次 |
| 最近记录: |