如何在 Pandas 中獲得兩列之間的相關性?
我們可以使用.corr()方法在 Pandas 中獲取兩列之間的相關性。我們來看一個示例,瞭解如何應用此方法。
步驟
- 建立一個二維、大小可變、可能是異構的表格資料 df。
- 列印輸入的 DataFrame df。
- 初始化兩個變數 col1 和 col2,並將要找出其相關性的列分配給他們。
- 使用df[col1].corr(df[col2]) 找出 col1 和 col2 之間的關係,並將關係值儲存在一個變數 corr 中。
- 列印相關性值 corr。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
col1, col2 = "x", "y"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)
col1, col2 = "x", "x"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)
col1, col2 = "x", "z"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)
col1, col2 = "y", "x"
corr = df[col1].corr(df[col2])
print "Correlation between ", col1, " and ", col2, "is: ", round(corr, 2)輸出
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Correlation between x and y is: 0.41 Correlation between x and x is: 1.0 Correlation between x and z is: 0.72 Correlation between y and x is: 0.41
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP