हम पैंडास में दो कॉलम के बीच सहसंबंध प्राप्त करने के लिए .corr() विधि का उपयोग कर सकते हैं। आइए एक उदाहरण लें और देखें कि इस विधि को कैसे लागू करें।
चरण
- दो-आयामी, आकार-परिवर्तनीय, संभावित विषम सारणीबद्ध डेटा, df बनाएं।
- इनपुट डेटाफ्रेम, 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