網站首頁 編程語言 正文
解讀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(皮爾遜相關系數)。
下面以一個觀眾對電影評分的例子說明
每一行表示一個觀眾對所有電影的評分,每一列表示所有觀眾對一部電影的評分。
然后分別計算第一位觀眾和其他觀眾的相關性 和第一部電影和其它電影的相關性。
代碼如下
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
similarity_with_other_movies
從結果可以看出,user1和user4的相關性最高,說明他們對每部電影的評分最接近,或者說他們的喜歡電影的類型最接近;《The Shawshank Redemption》和《Forrest Gump》的相關性為1,說明后者的評分和前者最接近。
原文鏈接:https://blog.csdn.net/w1301100424/article/details/98473560
相關推薦
- 2022-08-28 PostgreSQL常用字符串分割函數整理匯總_PostgreSQL
- 2022-04-18 antd4.*表格 Each child in a list should have a uniqu
- 2022-06-21 Oracle新增和刪除用戶_oracle
- 2022-11-03 python數據分析基礎知識之shape()函數的使用教程_python
- 2022-02-27 Spring Boot -- 創建工程時 Spring Initializr 報錯 Error:co
- 2022-08-03 Python如何對文件進行重命名_python
- 2022-10-16 Ant?Design?組件庫按鈕實現示例詳解_React
- 2022-09-22 k8s 存儲卷之 PV & PVC
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支