将多重索引数据框转换为LaTeX

2 投票
2 回答
1084 浏览
提问于 2025-04-20 13:37

我正在尝试使用ipython的nbconvert把一个多层索引的Pandas数据框导出为latex格式,但多层索引的行显示得完全不对。我在代码开头使用了以下代码,以便正确转换为latex(我在某个地方找到的,但记不清是哪里了):

from sympy import latex
from IPython.display import HTML, Latex, display, Math
pd.set_option('display.notebook_repr_html', True)
def _repr_latex_(self):
    return "\\begin{center} %s \end{center}" % self.to_latex()
pd.DataFrame._repr_latex_ = _repr_latex_  # monkey patch pandas DataFrame

虽然我的groupby代码比较复杂,但我也用一些简单的代码进行了测试,比如:

a = np.array([[1, 3, 4, 5],
             [1, 5, 36, 2],
             [3, 6, 23, 5],
             [2, 2, 1, 6],
             [2, 5, 1, 99]])
df = pd.DataFrame(a, columns=['A','B','C','D'])
df.groupby(by=['A','D']).sum()

这样做的结果是

    \begin{center} \begin{tabular}{lrr}
\toprule
{} &  B &   C \\
A D  &    &     \\
\midrule
1 2  &  5 &  36 \\
  5  &  3 &   4 \\
2 6  &  2 &   1 \\
  99 &  5 &   1 \\
3 5  &  6 &  23 \\
\bottomrule
\end{tabular}
 \end{center}

这个例子只展示了第一个问题,这个输出会把多层索引堆叠在一起,但我找不到在输出之前格式化它的方法。(我需要生成很多这样的表格,所以在latex里格式化真的很麻烦)。而且如果有几个多层索引,表格就会变得完全无法阅读。第二个大问题是,ipython用display()显示这些表格时,能够很好地调整列宽以适应屏幕,但在latex中却超出了页面宽度,导致大部分表格内容都消失了。

我到处寻找nbconvert更好的格式化解决方案,但什么也没找到。如果你也遇到过这个问题,或者知道解决这两个问题的办法,请告诉我。

附注:我使用的是python 2.7.7 Anaconda 2.0.1(64位)和最新版本的pandas(0.14.1)以及ipython(2.2.0)。

2 个回答

0

奇怪。我今晚尝试了类似的 .to_html() 方法,结果发现输出的是 HTML 代码,而不是把它显示出来。看起来和你的结果很像。

顺便说一下。我是在 Mac 上使用 IPython 2.2 和 Anaconda 模块。

3

我觉得这是to_latex里的一个错误,而且res.T.to_latex()的结果看起来也不对。

一个解决办法可能是修改索引:

In [11]: res = df.groupby(by=['A','D']).sum()

In [12]: res.index = res.index.map(lambda x: ' & '.join(map(str, x)))

In [13]: res.index.name = 'A & D'

In [14]: res.columns.values[0] = ' & ' + res.columns[0]

In [15]: print res.to_latex(escape=False)  # the whole point is not to escape the &s
\begin{tabular}{lrr}
\toprule
{} &   & B &   C \\
\midrule
A & D  &       &     \\
1 & 2  &     5 &  36 \\
1 & 5  &     3 &   4 \\
2 & 6  &     2 &   1 \\
2 & 99 &     5 &   1 \\
3 & 5  &     6 &  23 \\
\bottomrule
\end{tabular}

撰写回答