gpt4 book ai didi

python - nbconvert 多索引数据帧到 latex

转载 作者:太空宇宙 更新时间:2023-11-04 01:14:07 26 4
gpt4 key购买 nike

我正在尝试使用 ipython 的 nbconvert 将多索引 Pandas DataFrame 导出到 latex 但是多索引行都出错了。我在代码开头使用以下代码正确转换为 latex (我在 SO 的某处找到它但不记得在哪里):

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 搜索了一个更好的格式化解决方案,但一无所获。如果您也遇到过这个问题,或者您知道这两个问题中任何一个的解决方案,请告诉我。

pd:我正在使用 python 2.7.7 Anaconda 2.0.1(64 位)和最新版本的 pandas(0.14.1) 和 ipython(2.2.0)。

最佳答案

我认为这是 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}

关于python - nbconvert 多索引数据帧到 latex ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25734454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com