Mathew K Analytics

Lesson 49 · Mastering Pandas

Understanding Data Correlation and Heatmap Visualization Using Python and Pandas

In this lesson, you will learn how to explore relationships between features using correlation coefficients and visualize these connections with heatmaps.…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Data Correlation and Heatmaps in Pandas#

In this lesson, you will learn how to explore relationships between features using correlation coefficients and visualize these connections with heatmaps.

import warnings; warnings.filterwarnings('ignore')  # Ignore warnings for clean output
import numpy as np
np.random.seed(42)

Dataset Introduction: The Titanic Dataset#

We will use the Titanic dataset, a classic for learning data analysis. This dataset contains information about passengers like age, fare, and survival status.

# Data setup (Titanic Dataset)
import pandas as pd
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
(891, 12)
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  
# Quick data info
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB
None
# Select only numeric columns for correlation
numeric_df = df.select_dtypes(include='number')
print(numeric_df.columns.tolist())
['PassengerId', 'Survived', 'Pclass', 'Age', 'SibSp', 'Parch', 'Fare']

What is Correlation?#

Correlation shows how two variables move together. A correlation of 1.0 means both always move in the same direction. A value of -1.0 means they move in exactly opposite directions. A correlation near 0 means there is little or no relationship.

# Basic correlation matrix
corr_matrix = numeric_df.corr()
print(corr_matrix)
             PassengerId  Survived    Pclass       Age     SibSp     Parch  \
PassengerId     1.000000 -0.005007 -0.035144  0.036847 -0.057527 -0.001652   
Survived       -0.005007  1.000000 -0.338481 -0.077221 -0.035322  0.081629   
Pclass         -0.035144 -0.338481  1.000000 -0.369226  0.083081  0.018443   
Age             0.036847 -0.077221 -0.369226  1.000000 -0.308247 -0.189119   
SibSp          -0.057527 -0.035322  0.083081 -0.308247  1.000000  0.414838   
Parch          -0.001652  0.081629  0.018443 -0.189119  0.414838  1.000000   
Fare            0.012658  0.257307 -0.549500  0.096067  0.159651  0.216225   

                 Fare  
PassengerId  0.012658  
Survived     0.257307  
Pclass      -0.549500  
Age          0.096067  
SibSp        0.159651  
Parch        0.216225  
Fare         1.000000  
# Find which features are most related to survival
print(corr_matrix['Survived'].sort_values(ascending=False))
Survived       1.000000
Fare           0.257307
Parch          0.081629
PassengerId   -0.005007
SibSp         -0.035322
Age           -0.077221
Pclass        -0.338481
Name: Survived, dtype: float64
# Visualize the correlation matrix with a heatmap
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt='.2f')
plt.title('Correlation Heatmap (Titanic Dataset)')
plt.show()
No description has been provided for this image

Optional: Focus on Top Correlations Only#

Sometimes, you want to see only the strongest or most interesting relationships. Let us filter for large absolute correlations (ignoring the diagonal).

# List feature pairs with high absolute correlation (excluding the diagonal)
corr_pairs = corr_matrix.unstack()
sorted_pairs = corr_pairs[(corr_pairs.abs() > 0.5) & (corr_pairs.index.get_level_values(0) != corr_pairs.index.get_level_values(1))]
print(sorted_pairs.sort_values(ascending=False))
Pclass  Fare     -0.5495
Fare    Pclass   -0.5495
dtype: float64
# Visualize pairwise relationships with Seaborn pairplot
sns.pairplot(numeric_df[['Survived', 'Fare', 'Age', 'Pclass']], diag_kind='kde')
plt.suptitle('Pairwise Plots of Key Titanic Features', y=1.02)
plt.show()
No description has been provided for this image

How Correlation Informs Feature Engineering#

Features with strong correlation might overlap in what they tell us, so including both may not always help. But, finding relationships helps us create new insights or spot problems such as data leakage.

# Mini-challenge: Remove one column with high correlation to another
# Let us drop 'SibSp' if it is very similar to 'Parch', for example
reduced_df = numeric_df.drop('SibSp', axis=1)
print(reduced_df.head(2))
   PassengerId  Survived  Pclass   Age  Parch     Fare
0            1         0       3  22.0      0   7.2500
1            2         1       1  38.0      0  71.2833
# Heatmap after column removal
corr_new = reduced_df.corr()
plt.figure(figsize=(7, 5))
sns.heatmap(corr_new, annot=True, cmap='coolwarm', fmt='.2f')
plt.title('Correlation Heatmap After Feature Removal')
plt.show()
No description has been provided for this image
# Handling missing data before correlation (if needed)
missing_cols = numeric_df.columns[numeric_df.isnull().any()].tolist()
print('Columns with missing values:', missing_cols)
filled_df = numeric_df.fillna(numeric_df.mean())
print('Any NaN still? ', filled_df.isnull().any().any())
Columns with missing values: ['Age']
Any NaN still?  False

Troubleshooting: Why Am I Getting All Zeros or NaNs?#

If you ever see a correlation matrix with only zeros or NaN values, check your data! Maybe you tried to correlate text columns, have missing values, or used an empty DataFrame.

# Intentional error: Try correlating object columns
try:
    obj_df = df.select_dtypes(include='object')
    print(obj_df.corr())
except Exception as e:
    print('Error:', e)
    
Error: could not convert string to float: 'Braund, Mr. Owen Harris'

Recap: Key Takeaways#

  • Correlation measures how strongly two numeric features move together.
  • Use heatmaps and pairplots to spot relationships, outliers, and redundant features.
  • Always check for missing values before you calculate correlations.

Practice & Challenge#

Can you use the same approach to explore the Iris or Tips datasets?

Share your favorite correlation findings or post your questions in the video comments!

If you found this lesson helpful, like and subscribe for more pandas tutorials!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.