从函数返回多个值时,有没有办法保留 pandas 数据框的网格输​​出?

Is there a way to keep the grid output of a pandas dataframe when returning multiple values from a function?

全部,

当 return 从一个函数中获取多个值时,是否有办法保持 pandas 数据框或 statsmodels 回归摘要的网格显示?

def lr(x,y,df):
    x=sm.add_constant(x)
    est=sm.OLS(y,x)
    est=est.fit()
    return (df.corr(),
            print('\n'),
            print('\n'),
            est.summary())

以上功能为例。如果我只是 returning df.corr() 它会保留查看 pandas 数据帧时通常出现的网格。如果我只使用 return est.summary(),结果相同。然而,当我想要 return 两者时,它们在美学上就变得不那么令人愉悦了。我试过将它们都放在 print() 中,结果相同。请帮忙!

编辑:

def lr(x,y,df):
x=sm.add_constant(x)
est=sm.OLS(y,x)
est=est.fit()
return (HTML(df.corr()._repr_html_()),
        HTML(est.summary()._repr_html_()))

returns(IPython.core.display.HTML对象,IPython.core.display.HTML对象)

def lr(x,y,df):
x=sm.add_constant(x)
est=sm.OLS(y,x)
est=est.fit()
return (HTML(df.corr()._repr_html_() + est.summary()._repr_html_()))

给出了我下面评论中列出的错误

谢谢!

df.corr()est.summary() 都是 return DataFrame 个对象。

当函数 return 只是一个时,Jupyter 通过 运行 底层方法 _repr_html_ 显示该对象,return 是漂亮 html table 然后显示出来。您可以通过以下方式做同样的事情:

from IPython.core.display import HTML

HTML(df.corr()._repr_html_())

但是,当您 return 它们都包含在一个元组中时,Jupyter 会在元组上运行 _repr_ 方法,其中只有 returns 文本格式不正确。如果您从函数中进行赋值:

my_results = lr(x, y, df)

my_results[0]

你会再次得到漂亮的格式。或者:

my_results[1]

格式也很漂亮。要同时获得两者,请执行以下操作:

from IPython.core.display import HTML

HTML(df.corr()._repr_html_() + est.summary()._repr_html_())