我正在尝试使用 ipython 的 nbconvert 将多索引 Pandas DataFrame 导出到乳胶
但多索引行结果都是错误的。
我在代码开头使用以下代码来正确转换为乳胶(我在 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}
此示例仅显示第一个问题,此输出将显示多索引堆叠在另一个之上,但我找不到在输出之前对其进行格式化的方法。 (我正在制作许多此类大型表格,因此在乳胶本身上进行格式化会[并且是]一种痛苦)。还有几个多索引,它变得完全不可读。第二个大问题是 Ipython 使用 display() 渲染这个表格,确实很好地调整了屏幕的列宽,但在乳胶上它超出了页面宽度,并且大部分表格都丢失了。
我已经到处寻找更好的 nbconvert 格式化解决方案,但找不到任何东西。如果您也遇到过这个问题,或者您知道这两个问题的解决方案,请告诉我。
pd:我正在使用 python 2.7.7 Anaconda 2.0.1(64 位)以及最新版本的 pandas(0.14.1) 和 ipython(2.2.0)。