LearnPy Hub
Machine LearningAdvancedLesson 29 of 32

Exploratory Data Analysis (EDA)

Watch the ideaGetting to know a dataset
df.shape
df
depthoursscore
0CSE1285
1cse552
2EEENaN78
3BBA231
4EEE6069
(5, 3)

A new dataset arrives. Before any model, take a first look: how many rows and columns?

1Level 1 · BasicsBasics

Before you train any model, you need to know your data. Exploratory Data Analysis (EDA) is the detective work you do first: how big is the dataset, what does each column hold, what's missing or wrong, how are the values spread out, and which columns move together? Good EDA catches problems that would quietly ruin a model, and it often answers the real question before any machine learning is needed.

This lesson is about looking and measuring: every standard pandas and Matplotlib command you need to understand a dataset, with a runnable example for each and an explanation of what the output tells you. Fixing the problems you find (filling gaps, removing duplicates and outliers, encoding text, scaling) is taught in the "pandas: Cleaning & Analysis" lesson, and turning a clean table into a trained model is taught in the "ML Project: Classification" and "ML Project: Regression" lessons.

These examples use pandas, Matplotlib and scikit-learn. The first run downloads them into your browser, so give it a moment.

The EDA checklist

Work through the same questions every time, in this order:

StepQuestionMain tools
0. LoadCan I read the data into a DataFrame?pd.read_csv(), load_wine(as_frame=True)
1. First lookHow many rows and columns? What type is each column?df.shape, df.head(), df.info(), df.dtypes, df.describe()
2. Data qualityWhat's missing, duplicated or badly typed?df.isna().sum(), df.duplicated().sum(), nunique(), unique()
3. One column at a timeWhat's typical? How spread out? Any strange values?describe(), skew(), quantile(), value_counts(), histograms, box plots
4. OutliersWhich values are far from the rest, and are they real?IQR rule, z-scores, box plots
5. RelationshipsWhich columns move together? Do groups differ?df.corr(), groupby, pd.crosstab, scatter plots, heatmap, scatter_matrix
6. The targetIf you'll predict a column, how are its classes balanced?value_counts(normalize=True)
7. ReportWhat did I find, and what must be fixed before modelling?a short written list of findings

Step 0: loading the data

Real projects usually start from a CSV file: df = pd.read_csv("students.csv"). In this lesson the data has to live inside the code, so we use two tricks that behave exactly like a file:

  • CSV text with io.StringIO. StringIO wraps a string so pandas can read it as if it were a file: pd.read_csv(io.StringIO(csv_text)). Empty cells become NaN ("Not a Number"), pandas' marker for a missing value.
  • A dataset bundled with scikit-learn. load_wine(as_frame=True) returns an object whose .frame is a ready DataFrame with all the feature columns plus a target column. Others that need no internet: load_iris, load_breast_cancer, load_diabetes, load_digits.

The target in these datasets is stored as numbers (0, 1, 2). .target_names tells you what each number means, and df["target"].map(dict(enumerate(names))) swaps the numbers for readable labels.

Step 1: the first look

CommandWhat it shows
df.shapea pair (rows, columns). Not a method, so no brackets.
df.head(n) / df.tail(n)the first / last n rows (5 if you leave n out)
df.sample(n, random_state=1)n random rows. Files are often sorted, so the top rows can mislead; a random sample is fairer. random_state makes it pick the same rows every run.
df.columnsthe column names; .tolist() prints them as a plain list
df.dtypesthe type of each column: int64 (whole numbers), float64 (decimals, and any number column with a gap), object or str (text)
df.info()everything above in one table: row count, each column's non-null count and type, and memory used
df.memory_usage(deep=True)bytes used by each column; deep=True also measures the text inside text columns

Reading info(): the line RangeIndex: 14 entries is the number of rows. In the column list, a Non-Null Count lower than the row count means that column has gaps. A column you expect to be numeric but which shows object or str usually has a stray symbol such as "12 hrs" or "N/A" in it. Also notice that a whole-number column with a gap becomes float64, because NaN is a float.

describe(): a summary of every column

df.describe() summarises the number columns. Each row of its output means:

RowMeaningWhat to check
countvalues that are not missinglower than the row count = gaps
meanthe averagefar from the 50% row = skew or outliers
stdstandard deviation: the typical distance of a value from the mean0 or tiny = a useless constant column
min / maxsmallest and largest valuesimpossible values (60 study hours a day, age −3)
25% / 50% / 75%the quartiles: a quarter, half and three quarters of the values are below these. 50% is the median.the middle half of the data lies between 25% and 75%

For text columns, use df.describe(include="object") (or exclude="number", which also works in the newest pandas, where text has the str type). Its rows are count, unique (how many different values), top (the most common value) and freq (how often top appears). df.describe(include="all") puts every column in one table; the cells that don't apply (a mean of text) show NaN.

Step 2: data quality

  • Missing values: df.isnull() and df.isna() are the same thing: a table of True where a value is missing. Adding .sum() counts the Trues per column, and df.isna().mean() * 100 gives the percentage missing. A column that's 70% empty may be useless; one that's 2% empty can usually be fixed.
  • The opposite: df.notnull() (or notna()) is True where a value is present. df.notnull().sum() gives the same numbers as the Non-Null Count in info().
  • Which rows? df[df.isna().any(axis=1)] shows every row with at least one gap. axis=1 means "look across each row".
  • Duplicates: df.duplicated() marks a row True when an identical row appeared earlier; .sum() counts them. df[df.duplicated(keep=False)] shows every copy, including the first.
  • Inconsistent text: "CSE", "cse" and "CSE " look like three departments to pandas. Print df["dept"].unique() to spot them.

Write each problem down. You'll fix them with fillna, drop_duplicates and .str.strip().str.upper() in the Cleaning lesson; EDA's job is to find them all first.

Unique values and counts

CommandReturnsUse it to
df.nunique()the number of different values in each columnspot ID columns (unique in every row) and constant columns (1 value)
df["dept"].unique()the different values themselvescatch spelling and spacing variants
df["dept"].value_counts()each value and how often it appears, most common firstsee which categories are common or rare
value_counts(normalize=True)the same, as shares that add up to 1compare with percentages
value_counts(dropna=False)also counts NaN as its own valuesee gaps inside a category column

The number of different values in a column is called its cardinality. A text column with very high cardinality (a name, an email) is usually an identifier, not a useful feature.

Splitting number columns from category columns

Numbers and categories are explored with different tools, so split the column names first:

num_cols = df.select_dtypes(include="number").columns.tolist()
cat_cols = df.select_dtypes(exclude="number").columns.tolist()

select_dtypes keeps only the columns of the chosen types. Then loop over num_cols for describe(), histograms and box plots, and over cat_cols for value_counts() and bar charts. Watch for number columns that are really labels (an id, a postcode, a class number 0/1/2): their mean means nothing.

Step 3: one column at a time (univariate analysis)

Univariate means "one variable": you study each column on its own. For a number column, ask about its centre, its spread and its shape:

  • Skewness, df["col"].skew(), measures lopsidedness. 0 means symmetric. Positive means a long tail of large values (right-skewed, like incomes); negative means a long tail of small values. Beyond about +1 or −1 is strongly skewed, and the mean is pulled towards the tail, away from the median.
  • Kurtosis, df["col"].kurt(), measures how heavy the tails are. pandas reports it so that a normal bell curve scores 0. A large positive value means more extreme values than a bell curve would have; a negative value means a flat shape with short tails (a uniform spread scores about −1.2).
  • Quantiles, df["col"].quantile([0.05, 0.25, 0.5, 0.75, 0.95]), are cut points: 0.95 is the value 95% of rows are below. They describe the spread without being fooled by a single extreme value.

Then draw it:

PlotForCodeWhat you see
Histograma number columnax.hist(df["score"], bins=20)bars counting values in each range: the shape (bell, skewed, two peaks)
Box plota number columnax.boxplot(df["income"])box from Q1 to Q3, a line at the median, whiskers, dots for outliers
Count (bar) plota category columndf["dept"].value_counts().plot.bar()one bar per category, its height the count

Step 4: detecting outliers

An outlier is a value far from the rest. Two standard rules find them:

RuleHowGood for
IQR ruleIQR = Q3 − Q1; outlier if below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQRany shape, including skewed data. It's what a box plot draws.
z-scorez = (x − mean) / std: how many standard deviations a value is from the mean; outlier if |z| > 3roughly bell-shaped data with plenty of rows
q1, q3 = df["hours"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outliers = df[(df["hours"] < low) | (df["hours"] > high)]

Notice a weakness of z-scores: a huge outlier inflates the mean and the std it's measured against, so in a small dataset it can hide itself. The IQR rule uses quartiles, which one extreme value barely moves.

In EDA you detect and investigate outliers; you don't delete them yet. A typo (60 instead of 6) should be fixed; a genuinely brilliant student is real data. Removing or capping outliers is covered in the "pandas: Cleaning & Analysis" lesson.

Step 5: relationships between two columns (bivariate analysis)

ColumnsNumbersPicture
number vs numbercorrelation df["hours"].corr(df["score"])scatter plot
category vs numberdf.groupby("dept")["score"].agg(["mean", "median", "count"])box plot per group
category vs categorypd.crosstab(df["dept"], df["result"])grouped bar chart

Correlation (Pearson's r) runs from −1 to +1. Near +1 means both rise together, near −1 means one falls as the other rises, and near 0 means no straight-line relationship. As a rough guide, above 0.7 (or below −0.7) is strong and below 0.3 is weak. Two cautions: correlation only spots straight-line patterns, and correlation is not causation: ice-cream sales and drownings both rise in summer, but one doesn't cause the other.

pd.crosstab counts every combination of two categories. Add normalize="index" to turn each row into proportions, so groups of different sizes can be compared fairly.

Many columns at once (multivariate analysis)

  • Correlation matrix: df.corr(numeric_only=True) gives the correlation of every pair of number columns. numeric_only=True skips text columns. The diagonal is always 1 (a column with itself), and the table is mirrored across it.
  • Heatmap: ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1) colours that table so strong pairs jump out: red for positive, blue for negative, pale for near 0. Writing each number on its cell with ax.text makes it readable.
  • Scatter matrix: pd.plotting.scatter_matrix(df[cols]) draws a scatter plot for every pair of columns and a histogram of each column on the diagonal. It's the quickest way to see curved patterns and clusters that a single correlation number misses. Keep it to about 4–6 columns, or the plots get tiny.

Step 6: the target and class balance

If you'll train a model to predict a column (the target), check its balance with df["target"].value_counts(normalize=True). A dataset is imbalanced when one class is much rarer than the others. If 95% of rows are "pass", a model that always says "pass" scores 95% accuracy while learning nothing. That share of the biggest class is the baseline accuracy: any real model has to beat it. With imbalanced data you'll need the precision and recall from the scikit-learn lesson and a stratified train/test split, both used in the ML Project lessons.

Step 7: write the report

EDA ends with a short list of findings, for example: "1,000 rows, 8 columns; hours 4% missing; 12 duplicate rows; dept has spelling variants; income right-skewed (skew 1.9); one impossible hours value of 60; hours is the strongest predictor of score (r = 0.74); target 72% pass / 28% fail." That list becomes your to-do list for the Cleaning lesson and your starting point for the ML Project lessons. The last example below does a complete report on one dataset.

Key points: load data with read_csv or a bundled sklearn dataset; take a first look with shape, head/tail/sample, dtypes, info() and describe(); count gaps with isna().sum() and duplicates with duplicated().sum(); use nunique(), unique() and value_counts() for categories; split columns with select_dtypes; describe shape with skew(), kurt() and quantile(); draw histograms, box plots and bar charts; detect outliers with the IQR rule or z-scores (fix them later); compare columns with correlation, groupby, crosstab, a heatmap and scatter_matrix; check the target's balance; finish with a written list of findings.

See it in actionEDA in five lines

Watch a small table get checked: its size, the gaps, the averages and a group comparison.

Step-by-step

Try it yourselfExample 1: Loading data: CSV text and a built-in dataset

read_csv reads text wrapped in StringIO exactly like a file; the empty cell becomes NaN. load_wine(as_frame=True).frame is a ready DataFrame with 178 wines, 13 measurements and a target column (0, 1, 2), which map() turns into names.

example_1.py
Output appears here

Example 2: The first look: shape, head, tail, sample, dtypes, info

14 messy student records. Read info() carefully: hours, attendance, sleep and score have fewer than 14 non-null values, so they have gaps, and they became float64 because NaN is a float. id and gender have no gaps.

example_2.py
Output appears here
Fill in the blanks

Size and gaps

Fill the blanks so the program prints the table's size and the number of missing values in each column.

blanks.py
import pandas as pd
df = pd.DataFrame({
    "dept": ["CSE", "EEE", "CSE", "BBA", "EEE", "CSE"],
    "hours": [12, 5, None, 2, 7, 9],
    "score": [85, 52, 78, 31, None, 74],
})
print(df.)
print(df.().sum())

Example 3: describe() for numbers, text and everything

The first table: hours has count 13 (one gap), a max of 60 (suspicious) and a mean of 10.3 far above its median of 7 (pulled up by that 60). The text table: dept has 5 unique values because 'cse' and 'CSE ' are counted separately; top is the most common value and freq its count. include='all' mixes both, with NaN where a statistic doesn't apply.

example_3.py
Output appears here
Fix the bug

The fill that didn't stick

This should fill the missing hours with the median and then print 0 missing values, but it still prints 1. Fix it.

buggy.py

Example 4: Missing values and duplicate rows

isnull() and isna() give identical counts. The percent table ranks the columns by how much is missing (7.1% = 1 of 14). notnull() counts the values that are present. Row 10 is an exact copy of row 5, so duplicated() finds 1; keep=False shows both copies.

example_4.py
Output appears here

Example 5: Unique values: nunique, unique and value_counts

nunique() shows id has 13 different values in 14 rows (the duplicate) and gender only 2. unique() reveals the spelling variants 'cse' and 'CSE '. value_counts(normalize=True) gives shares, and dropna=False adds a NaN row for the missing sleep value.

example_5.py
Output appears here
Fill in the blanks

Counts into shares

Fill the blanks so the program prints each department's share of the rows (CSE 0.5, EEE 0.333..., BBA 0.166...).

blanks.py
import pandas as pd
df = pd.DataFrame({
    "dept": ["CSE", "EEE", "CSE", "BBA", "EEE", "CSE"],
    "hours": [12, 5, None, 2, 7, 9],
    "score": [85, 52, 78, 31, None, 74],
})
print(df["dept"].(=True).round(3))

Example 6: Splitting number and category columns with select_dtypes

select_dtypes sorts the columns by type. id is stored as a number but is only a label, so it's removed before summarising. Then each group gets the right tool: describe() for numbers, value_counts() for categories.

example_6.py
Output appears here
Your turn

Count the outliers

Using the IQR rule (below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR), print how many values in sales are outliers. The answer is 2.

my_code.py

Example 7: Shape of a distribution: skew, kurtosis and quantiles

200 made-up students. hours is spread evenly (skew near 0, kurtosis near -1.2: flat, short tails). score is close to a bell (both near 0). income has a long right tail: skew well above 1, a large kurtosis, and a mean much higher than its median. The quantile table shows the 95% income is far above the 75%.

example_7.py
Output appears here
Fix the bug

Correlation with a text column

This should print the correlation table of the number columns, but it crashes because dept holds text. Fix the last line so it only uses number columns.

buggy.py
Your turn

Pass rate per department

A student passes with a score of 50 or more. Print each department's pass rate as a percentage with no decimals, in alphabetical order, like BBA 0%. Rows with no score count as not passed.

my_code.py

Example 8: Univariate plots: histogram, box plot and count plot

The histogram shows score's bell shape. The box plot of income has its median line low in the box and many dots above the top whisker: the right tail. The count plot shows how many students each department has.

example_8.py
Output appears here

Example 9: Bivariate analysis: scatter, box plot by group, groupby and crosstab

r = 0.88 between hours and score: a strong positive link, visible as an upward cloud in the scatter. groupby shows CSE scores a little higher on average. The crosstab counts pass/fail per department; normalize='index' turns each row into proportions so the departments compare fairly.

example_9.py
Output appears here

Example 10: Multivariate analysis: correlation heatmap and scatter matrix

On the wine data, the ranked pairs show flavanoids and total_phenols move together strongly (r = 0.86), and flavanoids falls as the class number rises (r = -0.85). The heatmap colours the whole table; the scatter matrix shows every pair, with each column's histogram on the diagonal, and the colours (one per class) show the three wine classes forming separate clusters.

example_10.py
Output appears here

Example 11: Detecting outliers with the IQR rule and z-scores

In hours, the IQR rule flags 60 and 25, but the z-score rule (|z| above 3) flags only 60: the 60 inflates the mean and std so much that 25 no longer looks extreme. In score, the IQR rule flags the score of 2 while its largest |z| is only 2.71, so the z-score rule finds nothing. In small data, extreme values hide themselves from z-scores. This only detects; fixing them is in the Cleaning lesson.

example_11.py
Output appears here

Example 12: The target: class balance and baseline accuracy

The breast cancer data has 357 benign and 212 malignant tumours: 62.7% vs 37.3%, mildly imbalanced. Always guessing 'benign' would already be 62.7% accurate, so a model must beat that baseline. The groupby shows the mean radius differs a lot between the classes: a promising feature.

example_12.py
Output appears here

Example 13: A complete EDA report on one dataset

Every step in order on 300 student records with planted problems (306 rows with the copies). Read the output from top to bottom: size and types, gaps (hours 4.9%), 6 duplicates, the 'cse' spelling variant, skewed income, three impossible hours values, and a 67/33 class balance. Notice how the three typos drag the hours-score correlation down from about 0.8 to 0.33: one more reason to investigate outliers. The findings list at the end is the to-do list for cleaning and modelling.

example_13.py
Output appears here

2Level 2 · IntermediateDeeper EDA: skew, bins and segments

Taming a skewed column

Money, populations and website visits are usually right-skewed: most values are small and a few are huge. On a histogram everything bunches at the left. Taking the logarithm, np.log1p(df["income"]), spreads the small values out and pulls the huge ones in, so the shape becomes much closer to a symmetric bell. log1p means log(1 + x), which also works when a value is 0.

Binning numbers into groups

pd.cut(df["hours"], bins=[0, 3, 6, 9, 12], labels=["0-3", "3-6", "6-9", "9-12"]) turns a number into a category, so you can ask "what's the average score of students who study 6-9 hours?". pd.qcut(df["income"], 4) makes four groups with the same number of rows each (quartiles).

Comparing segments

A pivot table summarises one number by two categories at once: df.pivot_table(index="dept", columns="band", values="score", aggfunc="mean"). Add margins=True for row and column totals. A groupby with agg can compute several statistics per group in one step, and pd.crosstab(..., normalize="index") turns counts into row percentages, which makes groups of different sizes comparable.

Missing values aren't always random

Check where values are missing: df["hours"].isna().groupby(df["dept"]).mean() gives the share of gaps in each department. If one department is missing far more data, filling the gaps with the overall median quietly hides that difference. Also compare the rows with a gap to the rows without one: df.groupby(df["hours"].isna())["score"].mean(). If students who left "hours" blank score lower, the gap itself carries information, and you may want a "was missing" flag column when you clean the data.

The log transform, binning and missing-value flags change the data, so they're applied in the cleaning step ("pandas: Cleaning & Analysis"); here you use them to see the data more clearly and decide what that step should do.

Example 14: A log transform for a skewed column

The raw incomes are strongly skewed (skew near 2). After log1p the skew is close to 0, and the histogram looks like a bell.

example_14.py
Output appears here

Example 15: Bins, a pivot table and segment comparisons

Study hours are cut into bands, then the average score is compared by department and band. Row percentages make the pass rates comparable.

example_15.py
Output appears here

Example 16: Where are the gaps? Missing values by group

Overall about 20% of hours are missing, but BBA is missing 36% and CSE under 10%. Students who left hours blank also score about 6 points lower, so the gaps are not random.

example_16.py
Output appears here

3Level 3 · AdvancedEDA for machine learning: the target, leakage and fair checks

Look at features through the target

Before training a classifier, compare each feature across the classes: df.groupby("species").mean(), or a box plot per class. A feature whose boxes barely overlap will be very useful to the model; one whose boxes sit on top of each other adds little. This is how you'd guess, before any model, that petal size separates iris species better than sepal width.

Data leakage

Leakage means a feature secretly contains the answer. A column called "grade_letter" when you're predicting "passed", or a "refund issued" column when predicting "will the customer complain", gives a model near-perfect scores in testing and useless predictions in real life. EDA red flag: a feature with a correlation of 0.99 with the target, or one that perfectly splits the classes. Ask "would I really know this value at the moment I make the prediction?"

Explore the training set only

Once you're building a model, split first, then explore and choose fill values on the training set. If the test rows influence your cleaning choices (for example the median used to fill gaps), your test score is no longer an honest estimate. The usual pattern:

train, test = train_test_split(df, test_size=0.25, random_state=0)
median = train["hours"].median()          # learned from train only
train["hours"] = train["hours"].fillna(median)
test["hours"] = test["hours"].fillna(median)

Multicollinearity

Two features with a correlation above about 0.9 (height in cm and height in inches, say) carry the same information. Some models handle that fine; others, like linear regression, give unstable results. Keeping one of them usually loses nothing.

Ranking features before modelling

With dozens of features, you can't draw a box plot for each. Instead, score how well each one separates two classes: the difference between the class means divided by the average of the class standard deviations. This is a standardised mean difference: about 0.2 is small, 0.8 is large, and above 2 the classes barely overlap. It gives you a shortlist of strong features and a list of near-useless ones before any model is trained. The model itself, and how to check which features it really uses, is covered in the "ML Project" lessons.

Example 17: EDA on the iris dataset, class by class

The averages per species and the box plots show that petal length separates the three species almost perfectly, while sepal width overlaps a lot. A model will lean on the petal features.

example_17.py
Output appears here

Example 18: Catching leakage, and filling gaps from training data only

The certificate column is recorded after the exam, so it gives the answer away; its near-perfect correlation with the target is the clue. Then the gaps are filled with the median of the training rows only.

example_18.py
Output appears here

Example 19: Ranking 30 features by how well they separate the classes

On the breast cancer data, the 'worst' size and concave-points features separate benign from malignant tumours by more than 2 standard deviations, while texture error and symmetry error barely differ. 15 feature pairs have a correlation above 0.95 (radius, perimeter and area measure nearly the same thing), a multicollinearity warning.

example_19.py
Output appears here
Common mistakeDon't jump from df.head() straight to training a model. Five rows can't show you a 5% gap, a duplicate, a spelling variant or an impossible value hidden in row 3,000: info(), isna().sum(), duplicated().sum(), unique() and describe() can. And don't "clean away" what you find without asking why: a blank income might mean "unemployed", and a huge purchase might be your best customer. When you'll train a model later, explore and choose fill values on the training set only, so no test information leaks in.
Exercise · predict the output

What does this print?

import pandas as pd
s = pd.Series(["CSE", "EEE", "CSE", None, "BBA", "CSE"])
print(s.nunique(), s.value_counts().iloc[0], s.isna().sum())
Quick quiz · 10 questions
1. What's the main purpose of EDA?
2. Which code counts the missing values in every column?
3. In df.info(), the hours column shows "13 non-null" but the DataFrame has 14 rows. What does that mean?
4. Which code lists the names of only the number columns?
5. A column's mean is 52,000 but its median is 31,000, and its skew is 2.3. What does that suggest?
6. With Q1 = 10 and Q3 = 20, above which value is a point an outlier by the 1.5 × IQR rule?
7. What does df["dept"].value_counts(normalize=True) return?
8. The correlation between two columns is −0.85. What does it mean?
9. Which plot draws a scatter plot for every pair of columns at once?
10. 90% of the rows in the target column are "pass". A model gets 90% accuracy. What should you conclude?
Ready to practice exploratory data analysis (eda)?

10 graded problems are waiting in Topic Practice.

Practice this topic →
Python Exploratory Data Analysis (EDA) · LearnPy Hub