解讀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)文章
tensorflow saver 保存和恢復(fù)指定 tensor的實例講解
今天小編就為大家分享一篇tensorflow saver 保存和恢復(fù)指定 tensor的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07Python+Selenium實現(xiàn)表單自動填充和提交
你是不是也厭倦了每天重復(fù)表單填寫的工作,是時候讓技術(shù)來幫助我們解放雙手了,下面小編就為大家介紹一下如何使用Selenium和Python來自動填充和提交表單2023-09-09pip matplotlib報錯equired packages can not be built解決
這篇文章主要介紹了pip matplotlib報錯equired packages can not be built解決,具有一定借鑒價值,需要的朋友可以參考下2018-01-01