python - 在 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 建议的矩阵不会直接显示矩阵。
解决方案
你大多拥有它。两个变化:
- 从 获取 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()
推荐阅读
- reactjs - 是否可以为 Reactjs 应用程序的单个组件及其所有依赖文件和插件(如构建版本)创建一个 js 文件
- sql-server - 连接到 SQL Server(Postgresql 数据库):使用什么作为主机名?
- sql - 简单案例语句返回 ORA-00937:不是单组组函数
- mysql - Spring - 无法使用 CRUD 存储库保存实体
- matplotlib - 不能使用 matplotlib 库?
- android - 为什么我不能在另一个文本视图上方添加一个文本视图?
- ios - 应用程序启动时如何处理 url?
- typo3 - TYPO3 从打字稿和流体模板渲染事件
- javascript - Using methods for the menu item callbacks in Google Apps Script
- collision-detection - 我想看看玩家是否在godot中的敌人之上或之下