解讀pandas.DataFrame.corrwith
解讀pandas.DataFrame.corrwith
pandas.DataFrame.corrwith用于計算DataFrame中行與行或者列與列之間的相關(guān)性。
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’ 表示計算列與列的相關(guān)性,axis=1或者axis=‘columns’ 表示計算行與行的相關(guān)性。
method是計算相關(guān)性的方法,這里采用pearson correlation coefficient(皮爾遜相關(guān)系數(shù))。
下面以一個觀眾對電影評分的例子說明

每一行表示一個觀眾對所有電影的評分,每一列表示所有觀眾對一部電影的評分。
然后分別計算第一位觀眾和其他觀眾的相關(guān)性 和第一部電影和其它電影的相關(guān)性。
代碼如下
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為例,計算他們之間的相關(guān)系數(shù),user1的均值是4,user2的均值是4.2:

這個結(jié)果與corrwith函數(shù)計算的結(jié)果一致。
similarity_with_other_users

similarity_with_other_movies

從結(jié)果可以看出,user1和user4的相關(guān)性最高,說明他們對每部電影的評分最接近,或者說他們的喜歡電影的類型最接近;《The Shawshank Redemption》和《Forrest Gump》的相關(guān)性為1,說明后者的評分和前者最接近。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
跟老齊學(xué)Python之用while來循環(huán)
while,翻譯成中文是“當(dāng)...的時候”,這個單詞在英語中,常常用來做為時間狀語,while ... someone do somthing,這種類型的說法是有的。2014-10-10
python分塊讀取大數(shù)據(jù),避免內(nèi)存不足的方法
今天小編就為大家分享一篇python分塊讀取大數(shù)據(jù),避免內(nèi)存不足的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
PyTorch中torch.manual_seed()的用法實例詳解
在Pytorch中可以通過相關(guān)隨機數(shù)來生成張量,并且可以指定生成隨機數(shù)的分布函數(shù)等,下面這篇文章主要給大家介紹了關(guān)于PyTorch中torch.manual_seed()用法的相關(guān)資料,需要的朋友可以參考下2022-06-06

