Python:在statsmodels摘要中不显示假人

2024-09-28 03:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用statsmodels创建一些回归输出:

import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.iolib.summary2 import summary_col
import numpy as np 
import pandas as pd 

x1 = pd.Series(np.random.randn(2000))
x2 = pd.Series(np.random.randn(2000))
aa_milne_arr = ['a', 'b', 'c', 'd', "e", "f", "g", "h", "i"]
dummy = pd.Series(np.random.choice(aa_milne_arr, 2000,))
depen = pd.Series(np.random.randn(2000))
df = pd.DataFrame({"y": depen, "x1": x1, "x2": x2, "dummy": dummy})
df['const'] = 1
df['xsqr'] = df['x1']**2  
mod = smf.ols('y ~ x1 + x2 + dummy', data=df)
mod2 = smf.ols('y ~ x1 + x2 + xsqr + dummy', data=df)
res = mod.fit()
res2 = mod2.fit()

print (summary_col([res,res2],stars=True,float_format='%0.3f',
                  model_names=['one\n(0)','two\n(1)'],
                  info_dict={'N':lambda x: "{0:d}".format(int(x.nobs)),
                             'R2':lambda x: "{:.2f}".format(x.rsquared)}))

它工作得很好,但是我有一个很大的数据集,其中有许多虚拟对象(比示例中的数据集多得多)。因此,我想从摘要输出(而不是从回归本身)中排除虚拟对象。有可能吗?在


Tags: importapiformatdfasnprandomdummy
1条回答
网友
1楼 · 发布于 2024-09-28 03:15:35

一种快速而肮脏的方法是首先在最终的summary_col中找到这些dummy索引,然后避免打印它们:

summary = summary_col(
    [res,res2],stars=True,float_format='%0.3f',
    model_names=['one\n(0)','two\n(1)'],
    info_dict={'N':lambda x: "{0:d}".format(int(x.nobs)),
    'R2':lambda x: "{:.2f}".format(x.rsquared)})

# As string
# summary_str = str(summary).split('\n')
# LaTeX format
summary_str = summary.as_latex().split('\n')

# Find dummy indexes
dummy_idx = []
for i, li in enumerate(summary_str):
    if li.startswith('dummy'):
        dummy_idx.append(i)
        dummy_idx.append(i + 1)

# Print summary avoiding dummy indexes
for i, li in enumerate(summary_str):
    if i not in dummy_idx:
        print(li)

不漂亮,但很管用。使用字符串格式:

^{pr2}$

使用乳胶格式:

\begin{table}
\caption{}
\begin{center}
\begin{tabular}{lcc}
\hline
           &   one   &   two    \\
           &   (0)   &   (1)    \\
\hline
\hline
\end{tabular}
\begin{tabular}{lll}
Intercept  & 0.070   & 0.067    \\
           & (0.069) & (0.071)  \\
x1         & 0.001   & 0.001    \\
           & (0.022) & (0.022)  \\
x2         & -0.024  & -0.025   \\
           & (0.022) & (0.022)  \\
xsqr       &         & 0.003    \\
           &         & (0.015)  \\
N          & 2000    & 2000     \\
R2         & 0.01    & 0.01     \\
\hline
\end{tabular}
\end{center}
\end{table}

相关问题 更多 >

    热门问题