Introduction
Correlation analysis helps us find how two things change together. It shows if one thing goes up when the other goes up or down.
Correlation analysis helps us find how two things change together. It shows if one thing goes up when the other goes up or down.
import pandas as pd correlation = df['column1'].corr(df['column2'])
import pandas as pd # Create sample data data = {'height': [150, 160, 170, 180], 'weight': [50, 60, 65, 80]} df = pd.DataFrame(data) # Calculate correlation corr = df['height'].corr(df['weight']) print(corr)
import numpy as np import pandas as pd # Random data with no relation np.random.seed(0) data = {'x': np.random.rand(100), 'y': np.random.rand(100)} df = pd.DataFrame(data) print(df['x'].corr(df['y']))
This program calculates how study hours and scores relate. A positive number means more study hours usually mean higher scores.
import pandas as pd # Sample data for study hours and scores data = {'study_hours': [1, 2, 3, 4, 5], 'scores': [50, 55, 65, 70, 80]} df = pd.DataFrame(data) # Calculate correlation correlation = df['study_hours'].corr(df['scores']) print(f"Correlation between study hours and scores: {correlation:.2f}")
Correlation does not mean one thing causes the other.
Values near 1 or -1 show strong relationships; near 0 means weak or no relationship.
Use correlation to understand data before building models.
Correlation shows how two variables move together.
It is a number between -1 and 1.
Positive means both go up, negative means one goes up while the other goes down.
x and y using NumPy?np.corrcoef() to compute correlation matrix.x and y is at position [0, 1] in the matrix.import numpy as np
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
correlation = np.corrcoef(x, y)[0, 1]
print("{:.2f}".format(round(correlation, 2)))y is exactly twice x, so they have a perfect positive linear relationship.import numpy as np x = [1, 2, 3] y = [4, 5] correlation = np.corrcoef(x, y)[0, 1] print(correlation)
x and y have lengths 3 and 2, which must be equal for correlation.hours_studied and exam_score. You calculate their correlation and get -0.85. What does this imply and what should you consider next?Pass the test and this pattern moves unknown