我发现并正在使用@mrandrewindrade很好的答案来显示波士顿住房数据的相关系数,当我注意到在 iPython 笔记本中使用样式化的熊猫数据框时,我注意到数据中使用的颜色映射background_gradient()没有正确计算CHAS数据。看起来B数据中的某些值也受到影响。
它在传递给background_gradient(cmap, axis=1)命令的轴中是正确的,但不是另一个轴。当您将该行更改为axis=0. 所有其他表格单元格似乎计算得很好。
有人可以帮助找出问题所在,我对正在发生的事情以及如何避免它感到困惑吗?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# load Boston housing data into a dataframe
from sklearn.datasets import load_boston
boston = load_boston()
bos = pd.DataFrame(boston.data, columns=boston.feature_names)
bos['MEDV'] = boston.target
bos.head()
Run Code Online (Sandbox Code Playgroud)
# using a styled panda's dataframe from /sf/answers/2962622911/
cmap = 'coolwarm'
def magnify():
return [dict(selector="th", props=[("font-size", "7pt")]),
dict(selector="td", props=[('padding', "0em 0em")]),
dict(selector="th:hover", props=[("font-size", "12pt")]),
dict(selector="tr:hover td:hover",
props=[('max-width', '200px'), ('font-size', '12pt')])
]
corr.style.background_gradient(cmap, axis=1)\
.set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
.set_caption("Hover to magify")\
.set_precision(2)\
.set_table_styles(magnify())
Run Code Online (Sandbox Code Playgroud)
为了帮助突出这里的问题,绘制了与 seaborn 热图相同的数据:
# calculating and plotting the correlation coeff's using a seaborn heatmap
corr = bos.corr()
sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, cmap='coolwarm')
Run Code Online (Sandbox Code Playgroud)