解读pandas.DataFrame.corrwith

 

解读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分别表示样本每个维度的值,表示样本均值。

以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,说明后者的评分和前者最接近。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程宝库

 一、什么是frame&frame切换?frame:HTML页面中的一种框架,主要作用是在当前页面中指定区域显示另一页面元素;frame切换:通俗的讲当你进入房子里面 ...