日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

解讀pandas.DataFrame.corrwith_python

作者:waifdzdn ? 更新時間: 2022-12-23 編程語言

解讀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,說明后者的評分和前者最接近。

原文鏈接:https://blog.csdn.net/w1301100424/article/details/98473560

欄目分類
最近更新