當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas Series.corr()用法及代碼示例

Pandas 係列是帶有軸標簽的一維ndarray。標簽不必是唯一的,但必須是可哈希的類型。該對象同時支持基於整數和基於標簽的索引,並提供了許多方法來執行涉及索引的操作。

Pandas Series.corr()函數計算與其他係列的相關性,排除缺失值。

用法: Series.corr(other, method=’pearson’, min_periods=None)

參數:
other:係列
method:{'pearson','kendall','spearman'}或可致電
min_periods:獲得有效結果所需的最少觀察數

返回:相關性:浮點數

範例1:采用Series.corr()函數查找給定係列對象與另一個對象的相關性。

# importing pandas as pd 
import pandas as pd 
  
# Creating the first Series 
sr1 = pd.Series([80, 25, 3, 25, 24, 6]) 
  
# Creating the second Series 
sr2 = pd.Series([34, 5, 13, 32, 4, 15]) 
  
# Create the Index 
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] 
  
# set the first index 
sr1.index = index_ 
  
# set the second index 
sr2.index = index_ 
  
# Print the first series 
print(sr1) 
  
# Print the second series 
print(sr2)

輸出:

現在我們將使用Series.corr()函數查找給定係列對象的基礎數據與其他對象之間的相關性。

# find the correlation 
result = sr1.corr(sr2) 
  
# Print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.corr()函數已成功返回給定係列對象的基礎數據之間的相關性。

範例2:采用Series.corr()函數查找給定係列對象與另一個對象的相關性。係列對象包含一些缺失值。

# importing pandas as pd 
import pandas as pd 
  
# Creating the first Series 
sr1 = pd.Series([51, 10, 24, 18, None, 84, 12, 10, 5, 24, 2]) 
  
# Creating the second Series 
sr2 = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) 
  
# Create the Index 
index_ = pd.date_range('2010-10-09', periods = 11, freq ='M') 
  
# set the first index 
sr1.index = index_ 
  
# set the second index 
sr2.index = index_ 
  
# Print the first series 
print(sr1) 
  
# Print the second series 
print(sr2)

輸出:

現在我們將使用Series.corr()函數查找給定係列對象的基礎數據與其他對象之間的相關性。

# find the correlation 
result = sr1.corr(sr2) 
  
# Print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.corr()函數已成功返回給定係列對象的基礎數據之間的相關性。在計算對象之間的相關性時,將跳過缺少的值。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Series.corr()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。