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

หาความสัมพันธ์เชิงสัมพันธ์ (Correlation) ระหว่างสองคอลัมน์ตัวเลขใน Pandas DataFrame

ใช้เมธอด corr() ของ Series เพื่อคำนวณสหสัมพันธ์พีอาร์สัน (Pearson correlation coefficient) ระหว่างสองคอลัมน์ตัวเลข ค่าอยู่ระหว่าง -1 ถึง 1

ขั้นตอน

  1. สร้าง DataFrame ที่มีคอลัมน์ตัวเลขสองคอลัมน์
  2. เลือกคอลัมน์ทั้งสองเป็น Series
  3. ใช้ col1.corr(col2) คำนวณสหสัมพันธ์
  4. พล็อตกระจาย (scatter) เพื่อดูความสัมพันธ์ภาพ

ตัวอย่างโค้ด

import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame({'lab': [1, 2, 3], 'value': [3, 4, 5]})
col1 = df['lab']
col2 = df['value']

plt.plot(col1, col2, 'o-')
correlation = col1.corr(col2)
print(f"สหสัมพันธ์ (Correlation coefficient): {correlation}")

plt.show()

ผลลัพธ์

สหสัมพันธ์ (Correlation coefficient): 1.0

ค่า 1.0 หมายถึงความสัมพันธ์เชิงเส้นสมบูรณ์แบบ (Perfect positive correlation) จุดข้อมูลเรียงบนเส้นตรง