设置
我有一个示例数据框:
import pandas as pd
df = pd.DataFrame.from_dict({'A':[1,2],'B':[3,4]})
我做了什么
使用to_latex() ,我可以将此数据框打印到 latex 表中。但是,我不希望包含索引列。 index_names
关键字应该会有所帮助。根据documentation :
index_names : bool, default True
Prints the names of the indexes.
我愿意:
df.to_latex(index_names=False)
我得到了什么
\begin{tabular}{lrr}
\toprule
{} & A & B \\
\midrule
0 & 1 & 3 \\
1 & 2 & 4 \\
\bottomrule
\end{tabular}
这与预期不符:0 和 1 不应该出现在两行的开头(在 \midrule
和 \bottomrule
之间)。我还尝试了 df.to_latex(),它提供了与之前相同的输出。
问题
看来设置index_names=False
对输出没有任何影响。 Link to a Google Colab notebook confirming this result .
如何打印没有索引列的 Pandas 数据框?
最佳答案
您需要index=False
,而不是index_names=False
:
>>> df.to_latex(index=False)
'\\begin{tabular}{rr}\n\\toprule\n A & B \\\\\n\\midrule\n 1 & 3 \\\\\n 2 & 4 \\\\\n\\bottomrule\n\\end{tabular}\n'
index_names=False
的作用是删除包含索引级别名称的列标题下方的行。仅当存在索引名称时才会发生这种情况。请参阅下面带有 idx
的行:
>>> df.rename_axis('idx')
A B
idx
0 1 3
1 2 4
>>> df.rename_axis('idx').to_latex()
'\\begin{tabular}{lrr}\n\\toprule\n{} & A & B \\\\\nidx & & \\\\\n\\midrule\n0 & 1 & 3 \\\\\n1 & 2 & 4 \\\\\n\\bottomrule\n\\end{tabular}\n'
>>> df.rename_axis('idx').to_latex(index_names=False)
'\\begin{tabular}{lrr}\n\\toprule\n{} & A & B \\\\\n\\midrule\n0 & 1 & 3 \\\\\n1 & 2 & 4 \\\\\n\\bottomrule\n\\end{tabular}\n'
关于python - 如何在没有索引的情况下将 Pandas 数据帧打印到 Latex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68820311/