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(皮尔逊相关系数)。
下面以一个观众对电影评分的例子说明:
每一行表示一个观众对所有电影的评分,每一列表示所有观众对一部电影的评分。然后分别计算第一位观众和其他观众的相关性
和第一部电影和其它电影的相关性。代码如下:
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:
r
x
y
=
∑
i
=
1
n
(
x
i
−
x
ˉ
)
(
y
i
−
y
ˉ
)
∑
i
=
1
n
(
x
i
−
x
ˉ
)
2
∑
i
=
1
n
(
y
i
−
y
ˉ
)
2
r_{xy}=\frac{\sum_{i=1}^{n}(x_{i}-\bar{x})(y_{i}-\bar{y})}{\sqrt{\sum_{i=1}^{n}(x_{i}-\bar{x})^2}\sqrt{\sum_{i=1}^{n}(y_{i}-\bar{y})^2}}
rxy=∑i=1n(xi−xˉ)2∑i=1n(yi−yˉ)2∑i=1n(xi−xˉ)(yi−yˉ)
其中,
n
n
n是样本的维度,
x
i
x_i
xi和
y
i
y_i
yi分别表示样本每个维度的值,
x
ˉ
\bar{x}
xˉ
和
y
ˉ
和\bar{y}
和yˉ表示样本均值。
以user1和user4为例,计算他们之间的相关系数,user1的均值是4,user2的均值是4.2:
r
u
s
e
r
1
−
u
s
e
r
4
=
1
×
0.8
+
1
×
0.8
+
(
−
1
)
×
(
−
1.2
)
+
(
−
1
)
×
(
−
0.2
)
+
0
×
(
−
0.2
)
1
2
+
1
2
+
(
−
1
)
2
+
(
−
1
)
2
+
0
0.
8
2
+
0.
8
2
+
(
−
1.
2
2
)
+
(
−
0.2
)
2
+
(
−
0.2
)
2
≈
0.8964
r_{user1-user4}=\frac{1\times0.8+1\times0.8+(-1)\times(-1.2)+(-1)\times(-0.2)+0\times(-0.2)}{\sqrt{1^2+1^2+(-1)^2+(-1)^2+0}\sqrt{0.8^2+0.8^2+(-1.2^2)+(-0.2)^2+(-0.2)^2}}\approx{0.8964}
ruser1−user4=12+12+(−1)2+(−1)2+00.82+0.82+(−1.22)+(−0.2)2+(−0.2)21×0.8+1×0.8+(−1)×(−1.2)+(−1)×(−0.2)+0×(−0.2)≈0.8964
这个结果与corrwith函数计算的结果一致。
similarity_with_other_users:
similarity_with_other_movies:
从结果可以看出,user1和user4的相关性最高,说明他们对每部电影的评分最接近,或者说他们的喜欢电影的类型最接近;《The Shawshank Redemption》和《Forrest Gump》的相关性为1,说明后者的评分和前者最接近。