Python for Artificial Intelligence Advanced 18 minutes

Exploratory Data Analysis

A small end-to-end project: from reading and cleaning the data to summarizing, plotting and drawing observations.

Your progress in the track0%

The workflow

  1. Load the data and check its dimensions and types.
  2. Check for missing and duplicate values.
  3. Summarize each variable and plot its distribution.
  4. Study the relationships between the variables.
  5. Document the observations and decisions.

An applied example

We use the Iris flower data included in scikit-learn:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris(as_frame=True)
df = iris.frame                      # 150 rows and 5 columns
df["species"] = df["target"].map(dict(enumerate(iris.target_names)))

print(df.shape)
print(df.isna().sum())
print(df.duplicated().sum())
print(df.describe())

Distributions

df.drop(columns="target").hist(figsize=(8, 6), bins=20)
plt.tight_layout()

Comparing classes

print(df.groupby("species")["petal length (cm)"].agg(["mean", "std"]))

You will notice that petal length differs clearly between the species, which suggests that it is a useful feature for classification.

Relationships

corr = df.drop(columns=["target", "species"]).corr()
print(corr.round(2))

fig, ax = plt.subplots()
for name, g in df.groupby("species"):
    ax.scatter(g["petal length (cm)"], g["petal width (cm)"], label=name, s=12)
ax.set_xlabel("petal length (cm)")
ax.set_ylabel("petal width (cm)")
ax.legend()

Outliers

A common rule considers a value an outlier if it falls outside the range \(Q_1 – 1.5\,IQR\) to \(Q_3 + 1.5\,IQR\):

col = df["sepal width (cm)"]
q1, q3 = col.quantile([0.25, 0.75])
iqr = q3 - q1
outliers = df[(col < q1 - 1.5 * iqr) | (col > q3 + 1.5 * iqr)]

Do not remove outliers automatically; inspect them first, because they may be important real cases.

Methodological warnings

  • Correlation does not imply causation.
  • If you will build a model, set aside the test data before making cleaning decisions based on statistics, to avoid data leakage.
  • Document every cleaning decision so that the analysis is reproducible.

Lesson terms

Outlier
An observation that differs greatly from the other values; it may be a measurement error or a rare real case.
Exploratory data analysis
Examining the data with summaries and plots to understand its structure and discover problems and patterns before modelling.
Correlation coefficient
A measure between -1 and 1 of the strength and direction of the linear relationship between two variables.

Abstract

Exploratory data analysis (EDA) is a step before building models whose goal is to understand the data: its dimensions, types, missing values, distributions, the relationships between its variables, and outliers. This lesson brings NumPy, pandas and Matplotlib together in an organized workflow, with the reminder that correlation does not imply causation.

Review questions

  1. Name four steps in exploratory data analysis.

    Checking the dimensions and types, counting missing values, summarizing the distributions, and studying relationships and outliers.

  2. Does a strong correlation between two variables mean that one causes the other?

    No; correlation does not prove causation, and there may be an influential third variable.

Sources and references

  1. 10 minutes to pandas — pandas documentation
  2. Wes McKinney — Python for Data Analysis, 3E (open access)

Complete the lesson