python - 熊猫样式背景渐变未显示在 jupyter 笔记本中
问题描述
我正在尝试打印具有背景渐变的熊猫数据框以提高可读性。我试图将我在文档中找到的内容应用到一个简单的用例中,但我无法让 jupyter notebook 实际打印带有颜色的表格 - 我一直在获取普通数据框。小例子:
import seaborn as sns
import pandas as pd
cm = sns.light_palette('green', as_cmap=True)
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3'])
df_res.loc['foo'] = [-.5*100, .3,.2]
df_res.loc['bar'] = [.3*100, .6,.9]
df_res.style.background_gradient(cmap=cm)
只是打印
我尝试了不同的打印技术,即
pretty = df_res.style.background_gradient(cmap=cm)
display(pretty)
或者
print(pretty)
或不同的颜色图
df_res.style.background_gradient(cmap='viridis')
但它们都不起作用。我还尝试了样式器是否可以正常工作,但至少 applymap 函数完成了它应该做的事情:
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
df_res.style.applymap(color_negative_red)
哪个打印
所以不知道为什么 background_gradient 似乎没有任何效果。
编辑:刚刚找到原因。这是一个简单的解决方法,但如果其他人遇到同样的问题,我会继续这样做。显然,pandas 使用元素作为对象而不是浮点数来初始化数据框。如此简单地将初始化更改为
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3']).astype('float')
解决了这个问题。
解决方案
您的数据框的 dtypes 是“对象”而不是数字。
首先,将数据框中的 dtype 更改为数字。
df_res.apply(pd.to_numeric).style.background_gradient(cmap=cm)
注意数据类型:
import seaborn as sns
import pandas as pd
cm = sns.light_palette('green', as_cmap=True)
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3'])
df_res.loc['foo'] = [-.5*100, .3,.2]
df_res.loc['bar'] = [.3*100, .6,.9]
df_res.info()
输出:
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, foo to bar
Data columns (total 3 columns):
Value 1 2 non-null object
Value 2 2 non-null object
Value 3 2 non-null object
dtypes: object(3)
memory usage: 144.0+ bytes
推荐阅读
- excel - 通过匹配名称将值从一个 excel 表粘贴到另一个
- java - GraalVM 原生镜像是提高整体应用程序性能还是只是减少启动时间?
- function - 当插值函数必须作为全局变量多次访问时优化 Julia 性能
- docker - 使用 Docker Image 运行量角器脚本
- java - 从 Firebase 存储获取上传时间
- python - 模型作品接受支持向量机 SVM 和线性判别分析
- javascript - react-image-magnify 减少高度和宽度
- node.js - Discord 机器人有时会做出反应
- mysql - 无法获取最近添加的记录 MySQL Python
- sql - 如果 :parameter 不为空,则 P.PRODUCT_NAME = :parameter else :parameter like 'seat%'