0

我使用 Python 分析 Jupyter Notebooks 中的数据,并将其转换为 PDF 以与合著者共享 ( jupyter nbconvert --to pdf)。我经常linearmodels.panel.results.compare()用来比较linearmodels包中的面板回归估计。但是,PDF 转换过程会将compare()输出转换为对 PDF 来说太宽的固定宽度字体(我将提供以下代码):

太宽的比较输出

我可以打印compare()将 Jupyter Notebook 转换为 PDF 时的输出吗?

一种可能的解决方案是将compare()输出转换为数据帧。pd.options.display.latex.repr = True当我转换为 PDF 时,该选项会漂亮地打印数据帧。例如:

数据框的漂亮打印

在笔记本中,compare()输出格式很好,看起来像一个数据框。但是,它不是数据框,我未能将其转换为数据框。

是否有替代解决方案来比较漂亮打印linearmodels包输出的结果?

以下是生成上述表格的代码(复制并粘贴到 Jupyter Notebook 代码单元中):

import pandas as pd
from linearmodels.panel import FamaMacBeth
from linearmodels.panel.results import compare

pd.options.display.latex.repr = True

from statsmodels.datasets import grunfeld
df = grunfeld.load_pandas().data
df.set_index(['firm','year'], inplace=True)

display(df.head())

table = {
    '(1)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit(),
    '(2)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit(),
    '(3)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit(),
    '(4)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit()
}

display(compare(table))
4

2 回答 2

1

compare返回一个PanelModelComparison。这个类有一个属性summary,它返回一个与statsmodels 中可用 linearmodels.compat.statsmodels.Summary的对象几乎相同的属性。实例有一个将表格转换为 LaTeX 的方法。SummarySummaryas_latex()

import pandas as pd
from linearmodels.panel import FamaMacBeth
from linearmodels.panel.results import compare

pd.options.display.latex.repr = True

from statsmodels.datasets import grunfeld
df = grunfeld.load_pandas().data
df.set_index(['firm','year'], inplace=True)

display(df.head())

table = {
    '(1)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit(),
    '(2)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit(),
    '(3)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit(),
    '(4)': FamaMacBeth.from_formula(formula='value ~ 1 + invest + capital', data=df).fit()
}

display(compare(table))
comparrison = compare(table)
summary = comparrison.summary
print(summary.as_latex())

这打印

\begin{center}
\begin{tabular}{lcccc}
\toprule
                               &         \textbf{(1)}        &         \textbf{(2)}        &         \textbf{(3)}        &         \textbf{(4)}         \\
\midrule
\textbf{Dep. Variable}         &            value            &            value            &            value            &            value             \\
\textbf{Estimator}             &         FamaMacBeth         &         FamaMacBeth         &         FamaMacBeth         &         FamaMacBeth          \\
\textbf{No. Observations}      &             220             &             220             &             220             &             220              \\
\textbf{Cov. Est.}             &  Fama-MacBeth Standard Cov  &  Fama-MacBeth Standard Cov  &  Fama-MacBeth Standard Cov  &  Fama-MacBeth Standard Cov   \\
\textbf{R-squared}             &            0.6964           &            0.6964           &            0.6964           &            0.6964            \\
\textbf{R-Squared (Within)}    &           -1.8012           &           -1.8012           &           -1.8012           &           -1.8012            \\
\textbf{R-Squared (Between)}   &            0.8660           &            0.8660           &            0.8660           &            0.8660            \\
\textbf{R-Squared (Overall)}   &            0.6964           &            0.6964           &            0.6964           &            0.6964            \\
\textbf{F-statistic}           &            248.83           &            248.83           &            248.83           &            248.83            \\
\textbf{P-value (F-stat)}      &            0.0000           &            0.0000           &            0.0000           &            0.0000            \\
\textbf{=====================} & =========================== & =========================== & =========================== & ===========================  \\
\textbf{Intercept}             &            114.16           &            114.16           &            114.16           &            114.16            \\
\textbf{ }                     &           (3.8390)          &           (3.8390)          &           (3.8390)          &           (3.8390)           \\
\textbf{capital}               &            0.1457           &            0.1457           &            0.1457           &            0.1457            \\
\textbf{ }                     &           (0.8510)          &           (0.8510)          &           (0.8510)          &           (0.8510)           \\
\textbf{invest}                &            6.3899           &            6.3899           &            6.3899           &            6.3899            \\
\textbf{ }                     &           (11.618)          &           (11.618)          &           (11.618)          &           (11.618)           \\
\bottomrule
\end{tabular}
%\caption{Model Comparison}
\end{center}

T-stats reported in parentheses
于 2022-01-05T10:17:37.033 回答
0

这是使用 Kevin S.'s 的替代方案.summary.as_latex()。下面的函数compare().summary用于创建一个数据框,该数据框jupyter nbconvert --to pdf转换为一个表格。

from io import StringIO
import warnings

def compare_df(x, fit_stats=['Estimator', 'R-squared', 'No. Observations']):
    with warnings.catch_warnings():
        warnings.simplefilter(action='ignore', category=FutureWarning)
        y = pd.read_csv(StringIO(compare(x, stars=True).summary.as_csv()), skiprows=1, skipfooter=1, engine='python')
    z = pd.DataFrame(
        data=y.iloc[:, 1:].values,
        index=y.iloc[:, 0].str.strip(),
        columns=pd.MultiIndex.from_arrays(
            arrays=[y.columns[1:], y.iloc[0][1:]],
            names=['Model', 'Dep. Var.']
        )
    )
    return pd.concat([z.iloc[11:], z.loc[fit_stats]])

PDF输出为:

漂亮的桌子

请注意,此解决方案需要pd.options.display.latex.repr = True.

于 2022-01-05T16:11:24.613 回答