Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหาความสัมพันธ์ (Correlation) ระหว่างสองคอลัมน์ใน Pandas


เราสามารถใช้เมธอด .corr() เพื่อหาความสัมพันธ์ระหว่างสองคอลัมน์ใน Pandas มาลองตัวอย่างดูวิธีใช้เมธอดนี้

ขั้นตอน

  • สร้างข้อมูลตารางสองมิติ df
  • พิมพ์ DataFrame อินพุต df
  • กำหนดตัวแปรสองตัว col1 และ col2 และกำหนดให้เป็นคอลัมน์ที่ต้องการหาความสัมพันธ์
  • หาความสัมพันธ์ระหว่าง col1 และ col2 โดยใช้ df[col1].corr(df[col2]) และเก็บค่า correlation ไว้ในตัวแปร corr
  • พิมพ์ค่า correlation 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