Chúng ta có thể sử dụng phương thức .corr() để lấy tương quan giữa hai cột trong Pandas. Hãy lấy ví dụ và xem cách áp dụng phương thức này.
Các bước
- Tạo dữ liệu bảng hai chiều, df.
- In DataFrame đầu vào, df.
- Khởi tạo hai biến, col1 và col2, và gán cho chúng các cột bạn muốn tìm tương quan.
- Tìm tương quan giữa col1 và col2 bằng cách sử dụng
df[col1].corr(df[col2])và lưu giá trị tương quan vào biếncorr. - In giá trị tương quan,
corr.
Ví dụ
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))
Kết quả
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