【问题标题】:nbconvert multiindex dataframes to latexnbconvert 多索引数据帧到乳胶
【发布时间】:2014-11-02 06:35:23
【问题描述】:

我正在尝试使用 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)。

【问题讨论】:

    标签: python pandas ipython ipython-notebook


    【解决方案1】:

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

    【讨论】:

    • 有一个关于按列行为的合并 PR(现已修复),我认为索引部分也将在 0.15 中修复。 github.com/pydata/pandas/pull/7982
    • df.reset_index().to_latex(index=False) 也是一个合理的解决方法吗?
    • @PaulH 当然更容易! :) 我想问题在于它是一个 MI 在 repr 中是否有任何价值。
    • 同意 -- 在笔记本中,我发现区分行标签和列值至关重要。一旦进入报告,我怀疑读者是否关心。因此,我已经使用了一段时间了。
    • 好人,感谢您的回答!顺便说一句,我发布的“猴子补丁”是使笔记本正确转换为乳胶的唯一方法还是有更优雅的方法?
    【解决方案2】:

    奇怪。我今晚用 .to_html () 尝试了类似的东西,却发现输出显示的是 html 而不是渲染它。在我看来,它与您的结果非常相似。

    FWIW。在 Mac 上使用 IPython 2.2 和 anaconda 模块。

    【讨论】:

    • 是的,这很正常。如果您使用的是 Ipython 笔记本,则在使用 display() 时,如果我没记错的话,默认调用是 to_html() 然后它会呈现它。我认为大多数 to_something 都是用于文件导出的。无论如何,在这种情况下,这不是问题,而是将数据结构化为这种新表示的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多