我有一个具有大量特征的数据集,因此分析相关矩阵变得非常困难。我想绘制一个相关矩阵,我们使用dataframe.corr()函数从pandas库中获得。pandas库是否提供了任何内置函数来绘制这个矩阵?
当前回答
试试这个函数,它也会显示相关矩阵的变量名:
def plot_corr(df,size=10):
"""Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
size: vertical and horizontal size of the plot
"""
corr = df.corr()
fig, ax = plt.subplots(figsize=(size, size))
ax.matshow(corr)
plt.xticks(range(len(corr.columns)), corr.columns)
plt.yticks(range(len(corr.columns)), corr.columns)
其他回答
可以使用matplotlib中的imshow()方法
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.imshow(X.corr(), cmap=plt.cm.Reds, interpolation='nearest')
plt.colorbar()
tick_marks = [i for i in range(len(X.columns))]
plt.xticks(tick_marks, X.columns, rotation='vertical')
plt.yticks(tick_marks, X.columns)
plt.show()
形成相关矩阵,在我的情况下,zdf是我需要执行相关矩阵的数据框架。
corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()
# Writing the output to a html file.
with open('test.html', 'w') as f:
print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)
然后我们可以截屏。或者将HTML转换为图像文件。
你可以通过绘制海洋出生的热图或熊猫的散射矩阵来观察特征之间的关系。
散射矩阵:
pd.scatter_matrix(dataframe, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
如果你想可视化每个特征的偏度,也可以使用海运配对图。
sns.pairplot(dataframe)
党Heatmap:
import seaborn as sns
f, ax = pl.subplots(figsize=(10, 8))
corr = dataframe.corr()
sns.heatmap(corr,
cmap=sns.diverging_palette(220, 10, as_cmap=True),
vmin=-1.0, vmax=1.0,
square=True, ax=ax)
输出将是特征的相关映射。参见下面的例子。
杂货店和洗涤剂之间的相关性很高。类似的:
高相关性产品:
杂货和洗涤剂。
相关性中等的产品:
牛奶和杂货 牛奶和洗涤剂。纸
低相关性产品:
牛奶和熟食 冷冻和新鲜。 冷冻熟食店。
从配对图中:你可以从配对图或散射矩阵中观察到相同的一组关系。但从这些可以判断数据是否正态分布。
注:上图为取自数据的同一张图,用于绘制热图。
你可以使用来自seaborn的heatmap()来查看b/w不同特征的相关性:
import matplot.pyplot as plt
import seaborn as sns
co_matrics=dataframe.corr()
plot.figure(figsize=(15,20))
sns.heatmap(co_matrix, square=True, cbar_kws={"shrink": .5})
当处理大量特征之间的相关性时,我发现将相关特征聚类在一起很有用。这可以用seaborn clustermap图来完成。
import seaborn as sns
import matplotlib.pyplot as plt
g = sns.clustermap(df.corr(),
method = 'complete',
cmap = 'RdBu',
annot = True,
annot_kws = {'size': 8})
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=60);
clustermap函数使用层次聚类将相关特征排列在一起并生成树状树状图。
在这个图中有两个值得注意的集群:
Y_des和dew.point_des Irradiance, y_seasonal和dew.point_seasonal
FWIW的气象数据,以产生这一数字可以访问与这木星笔记本。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录