使用Python进行相关性分析

栏目: Python · 发布时间: 5年前

内容简介:在数据分析时,经常会针对两个变量进行相关性分析。在Python中主要用到的方法是pandas中的corr()方法。我们以pandas.DataFrame.corr()为例进行详细说明:DataFrame.corr(method=’pearson’, min_periods=1)

在数据分析时,经常会针对两个变量进行相关性分析。在 Python 中主要用到的方法是pandas中的corr()方法。

  • corr():如果由数据框调用corr函数,那么将会计算每个列两两之间的相似度,返回DataFrame
  • corr(other):如果由序列调用corr方法,那么只是该序列与传入的序列之间的相关度,返回一个数值型,大小为相关度

我们以pandas.DataFrame.corr()为例进行详细说明:

DataFrame.corr(method=’pearson’, min_periods=1)

  • method : 指定相关系数的计算方式,可选性为:{‘pearson’,‘kendall’,‘spearman’}
    • pearson :皮尔逊相关系数
    • kendall :kendall秩相关系数
    • spearman :斯皮尔曼等级相关系数
  • min_periods : int, optional,指定每列所需的最小观察数,可选,目前只适合用在pearson和spearman方法。

参考链接: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.corr.html

线性相关关系通常采用皮尔逊(Pearson)相关系数r来度量连续变量之间线性相关强度

  • r>0:线性正相关
  • r<0:线性负相关
  • r=0:两个变量之间不存在线性关系(并不代表两个变量之间不存在任何关系)

线性相关系数|r|的取值范围:

  • 低度相关:0 <= |r| <= 0.3
  • 中度相关:3 <= |r| <= 0.8
  • 高度相关:8 <= |r| <= 1

相关性的可视化呈现:

from string import ascii_letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
sns.set(style="white")
 
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
                 columns=list(ascii_letters[26:]))
 
# Compute the correlation matrix
corr = d.corr()
 
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
 
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
 
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
 
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
            square=True, linewidths=.5, cbar_kws={"shrink": .5})
plt.show()

参考链接:


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python Machine Learning

Python Machine Learning

Sebastian Raschka / Packt Publishing - ebooks Account / 2015-9 / USD 44.99

About This Book Leverage Python' s most powerful open-source libraries for deep learning, data wrangling, and data visualization Learn effective strategies and best practices to improve and opti......一起来看看 《Python Machine Learning》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具