在IPython中使用自定义样式内部函数显示熊猫数据框

时间:2019-07-23 14:23:02

标签: python pandas ipython jupyter

在jupyter笔记本中,我有一个函数,可为张量流模型准备输入特征并确定矩阵。

在此功能内,我想显示一个具有背景渐变的相关矩阵,以更好地查看强相关的特征。

This答案显示了如何完全按照我的意愿去做。问题是从函数内部我无法获得任何输出,即:

def display_corr_matrix_custom():
    rs = np.random.RandomState(0)
    df = pd.DataFrame(rs.rand(10, 10))
    corr = df.corr()
    corr.style.background_gradient(cmap='coolwarm')

display_corr_matrix_custom()

显然不显示任何内容。通常,我使用IPython的display.display()函数。但是,在这种情况下,由于要保留自定义背景,因此无法使用它。

是否有另一种方法可以显示此矩阵(如果可能,不包含matplotlib)而不返回它?


编辑:在我的真实函数中,我还显示其他内容(作为数据描述),并且我想在精确的位置显示相关矩阵。此外,我的函数返回了许多数据帧,因此按@brentertainer的建议返回矩阵不会直接显示矩阵。

1 个答案:

答案 0 :(得分:1)

您大部分都拥有它。两项更改:

  • corr获取样式器对象。
  • 使用IPython的styler在函数中显示display.display()
def display_corr_matrix_custom():
    rs = np.random.RandomState(0)
    df = pd.DataFrame(rs.rand(10, 10))
    corr = df.corr()  # corr is a DataFrame
    styler = corr.style.background_gradient(cmap='coolwarm')  # styler is a Styler
    display(styler)  # using Jupyter's display() function

display_corr_matrix_custom()