700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python分析数据的相关性_使用Python进行相关性分析

python分析数据的相关性_使用Python进行相关性分析

时间:2023-09-13 21:00:46

相关推荐

python分析数据的相关性_使用Python进行相关性分析

在数据分析时,经常会针对两个变量进行相关性分析。在 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方法。

线性相关关系通常采用皮尔逊(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()

参考链接:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。