如何在没有索引的情况下将Pandas Dataframe 打印到Latex?

nbysray5  于 2023-06-04  发布在  其他
关注(0)|答案(2)|浏览(203)

设置

我有一个dataframe的例子:

import pandas as pd
df = pd.DataFrame.from_dict({'A':[1,2],'B':[3,4]})

我做了什么

使用to_latex(),我可以将这个数据框打印到一个latex表。但是,我不希望包含索引列。index_names关键字应该有帮助。根据documentation

**index_names:**bool,默认True

打印索引的名称。
我愿意:

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

如何打印出没有index列的Pandas Dataframe ?

nuypyhwy

nuypyhwy1#

您需要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'
lg40wkob

lg40wkob2#

pandas的新接口使用styler

import pandas as pd
df = pd.DataFrame.from_dict({'A': [1, 2], 'B': [3, 4]})
df.style.format(
    formatter="{:.2f}".format).format_index(
    axis=1, formatter="${}$".format).hide(
    axis=0).to_latex(
    buf="latex.tex")

相关问题