首页 > 解决方案 > 在 IPython 中使用自定义样式在函数内部显示熊猫数据框

问题描述

在一个 jupyter 笔记本中,我有一个函数可以为 tensorflow 模型准备输入特征和目标矩阵。

在这个函数中,我想显示一个带有背景渐变的相关矩阵,以更好地查看强相关特征。

这个答案显示了如何做到这一点,正是我想做的事情。问题是从函数内部我无法获得任何输出,即:

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 建议的矩阵不会直接显示矩阵。

标签: pythonpandasipythonjupyterpandas-styles

解决方案


你大多拥有它。两个变化:

  • 从 获取 Styler 对象corr
  • styler使用 IPython 在函数中显示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()

推荐阅读