【Pandas】相关性分析corrwith与corr

2023-05-16

        pandas有两类相关性分析的函数,分别是DataFrame的corrwith和Series的corr,注意这俩不能混用。corrwith用于计算DataFrame中行与行或者列与列之间的相关性,而corr用于计算Series之间的相关性,是corrwith的最小单元。

pandas.Series.corr

        pandas.Series.corr用于计算序列之间的相关性,比较简单。同一个DataFrame里的序列可以直接用corrwith来计算。不同DataFrame的话可以concat后用corrwith,也可以直接用序列的corr,例如:

corr = df['series1'].corr(df['series2'])

pandas.DataFrame.corrwith

        pandas.DataFrame.corrwith用于计算DataFrame中行与行或者列与列之间的相关性。

Parameters:

other:DataFrame, Series. Object with which to compute correlations.
axis: {0 or ‘index’, 1 or ‘columns’}, default 0. 0 or ‘index’ to compute column-wise, 1 or ‘columns’ for row-wise.
method:{‘pearson’, ‘kendall’, ‘spearman’} or callable.

        axis=0或者axis=‘index’ 表示计算列与列的相关性,axis=1或者axis=‘columns’ 表示计算行与行的相关性。method是计算相关性的方法,这里采用pearson correlation coefficient(皮尔逊相关系数)。

        下面以一个观众对电影评分的例子说明:

user_movie_ratings

        每一行表示一个观众对所有电影的评分,每一列表示所有观众对一部电影的评分。然后分别计算第一位观众和其他观众的相关性和第一部电影和其它电影的相关性。代码如下:

import pandas as pd
import numpy as np


data = np.array([[5, 5, 3, 3, 4], [3, 4, 5, 5, 4],
                 [3, 4, 3, 4, 5], [5, 5, 3, 4, 4]])
df = pd.DataFrame(data, columns=['The Shawshank Redemption',
                                 'Forrest Gump', 'Avengers: Endgame',
                                 'Iron Man', 'Titanic '],
                  index=['user1', 'user2', 'user3', 'user4'])
# Compute correlation between user1 and other users
user_to_compare = df.iloc[0]
similarity_with_other_users = df.corrwith(user_to_compare, axis=1,
                                          method='pearson')
similarity_with_other_users = similarity_with_other_users.sort_values(
    ascending=False)
# Compute correlation between 'The Shawshank Redemption' and other movies
movie_to_compare = df['The Shawshank Redemption']
similarity_with_other_movies = df.corrwith(movie_to_compare, axis=0)
similarity_with_other_movies = similarity_with_other_movies.sort_values(
    ascending=False)

        这里采用了pearson correlation coefficient:

​其中,n 是样本的维度,xi和yi分别表示样本每个维度的值,x ˉ 和 y ˉ 和表示样本均值。
以user1和user4为例,计算他们之间的相关系数,user1的均值是4,user2的均值是4.2:

        这个结果与corrwith函数计算的结果一致。
similarity_with_other_users:

user_correlation

similarity_with_other_movies:

movie_correlation

        从结果可以看出,user1和user4的相关性最高,说明他们对每部电影的评分最接近,或者说他们的喜欢电影的类型最接近;《The Shawshank Redemption》和《Forrest Gump》的相关性为1,说明后者的评分和前者最接近。
————————————————
参考:https://blog.csdn.net/w1301100424/article/details/98473560

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【Pandas】相关性分析corrwith与corr 的相关文章

随机推荐