Exploratory data analysis (EDA) in Python is the step where you find out what your data actually contains before you model it. This tutorial walks through a full EDA on a real dataset, with the exact output of every command, and ends on the kind of finding EDA exists to catch: a comparison that looks decisive and mostly disappears once you account for a hidden factor.
The data is the classic fuel-economy dataset of 398 cars from model years 1970 to 1982, as packaged in the seaborn-data repository (originally the UCI Auto MPG dataset). Everything ran on 20 November 2026 with pandas 3.0.5.
1. Load the data and check its shape
import pandas as pd
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv"
df = pd.read_csv(url)
print(df.shape)
print(df.dtypes.to_string())(398, 9)
mpg float64
cylinders int64
displacement float64
horsepower float64
weight int64
acceleration float64
model_year int64
origin str
name str398 rows and 9 columns. Seven are numeric and two are text (origin and name). Check that each type makes sense: cylinders is stored as a number but behaves like a category (3, 4, 5, 6 or 8).
2. Find missing values
print(df.isna().sum()[lambda s: s > 0].to_dict())
print(df[df.horsepower.isna()][["name", "model_year", "origin"]].to_string()){'horsepower': 6}
name model_year origin
32 ford pinto 71 usa
126 ford maverick 74 usa
330 renault lecar deluxe 80 europe
336 ford mustang cobra 80 usa
354 renault 18i 81 europe
374 amc concord dl 82 usaOnly horsepower has gaps: 6 of 398 rows, 1.5%. Always look at the rows, not just the count. Here the missing values do not cluster in one origin or year, so they are harmless here and do not need filling. If 30% were missing, you would have to ask why, and drop-or-fill would become a real decision (see the pandas guide to missing data).
We keep all 398 rows for the rest of this tutorial. pandas skips missing values automatically in mean, describe and corr, and a check for duplicate rows (df.duplicated().sum()) returns 0.
3. Summarise every numeric column
print(df.describe().round(2).T[["count", "mean", "std", "min", "50%", "max"]]) count mean std min 50% max
mpg 398.0 23.51 7.82 9.0 23.0 46.6
cylinders 398.0 5.45 1.70 3.0 4.0 8.0
displacement 398.0 193.43 104.27 68.0 148.5 455.0
horsepower 392.0 104.47 38.49 46.0 93.5 230.0
weight 398.0 2970.42 846.84 1613.0 2803.5 5140.0
acceleration 398.0 15.57 2.76 8.0 15.5 24.8
model_year 398.0 76.01 3.70 70.0 76.0 82.0Note the count column: horsepower has 392 values, the gap from section 2. What to look for: weight runs from 1,613 to 5,140 (a threefold range), and horsepower has a mean (104.5) above its median (93.5), a sign of a long right tail of powerful cars. Nothing impossible appears, such as negative weights or a 0 mpg.
4. Look at categories
print(df.origin.value_counts().to_dict())
print(df.cylinders.value_counts().sort_index().to_dict()){'usa': 249, 'japan': 79, 'europe': 70}
{3: 4, 4: 204, 5: 3, 6: 84, 8: 103}Cars from the USA make up about 63% of the data (249 of 398), and 3- and 5-cylinder cars are too rare (7 in total) to say anything about on their own. Keep that in mind: any group comparison rests on very different group sizes.
5. Check for outliers
q1, q3 = df.mpg.quantile([.25, .75])
iqr = q3 - q1
upper = q3 + 1.5 * iqr
print(round(upper, 1), int(((df.mpg < q1 - 1.5 * iqr) | (df.mpg > upper)).sum()))
print(df.loc[df.mpg.idxmax(), ["name", "mpg", "model_year"]].to_dict())46.2 1
{'name': 'mazda glc', 'mpg': 46.6, 'model_year': 80}The 1.5 x IQR rule flags a single car: the 1980 Mazda GLC at 46.6 mpg, just above the 46.2 limit. A statistical outlier is not an error. This is a small, efficient car from a plausible year, so it stays. Delete a value only when you can say why it is wrong.
6. Correlations
num = df.select_dtypes("number")
print(num.corr().mpg.drop("mpg").round(2).sort_values())
print(round(df[["horsepower", "weight"]].corr().iloc[0, 1], 2))weight -0.83
displacement -0.80
cylinders -0.78
horsepower -0.78
acceleration 0.42
model_year 0.58
0.86Weight has the strongest link to fuel economy (correlation -0.83): heavier cars do fewer miles per gallon. Displacement, cylinders and horsepower tell almost the same story, and horsepower and weight are themselves correlated at 0.86, so these predictors overlap heavily. Model year is positively related (0.58): later cars are more efficient. You can explore any pair with our correlation calculator.
7. Compare groups, and see the trap
print(df.groupby("origin").mpg.agg(["count", "mean", "median"]).round(1)) count mean median
origin
europe 70 27.9 26.5
japan 79 30.5 31.6
usa 249 20.1 18.5On the surface, Japanese cars average 30.5 mpg and American cars 20.1, a gap of 10.4 mpg. It is tempting to write “Japanese cars are far more efficient”. But EDA asks what else differs between the groups:
print(df.groupby("origin")[["weight", "horsepower", "cylinders"]].mean().round(0)) weight horsepower cylinders
origin
europe 2423.0 81.0 4.0
japan 2221.0 80.0 4.0
usa 3362.0 119.0 6.0The average American car weighs 3,362 pounds against 2,221 for the Japanese one, and has 6 cylinders rather than 4. Weight is the strongest driver of mpg, so part of the gap is simply that the groups contain different kinds of cars. This is called confounding.
8. Control for the confounder
Compare cars of similar weight only, using three weight bands:
df["weight_band"] = pd.cut(df.weight, [0, 2500, 3500, 6000],
labels=["<2500", "2500-3500", ">3500"])
print(df.pivot_table(index="weight_band", columns="origin", values="mpg",
aggfunc=["mean", "count"], observed=True).round(1)) mean count
origin europe japan usa europe japan usa
weight_band
<2500 30.7 31.7 29.0 45 62 40
2500-3500 23.0 26.0 21.9 23 17 102
>3500 21.0 NaN 15.1 2 NaN 107Among light cars (under 2,500 lb), Japan leads the USA by 2.7 mpg (31.7 against 29.0), and among mid-weight cars by 4.1 (26.0 against 21.9). That is far smaller than the headline 10.4. Some gap remains, but most of the raw difference came from weight. Two cautions: there are no Japanese cars above 3,500 lb and only 2 European ones, so that band cannot be compared, and weight bands are a rough control, not a full model.

9. An EDA checklist
- Shape and types: rows, columns, and whether each type matches its meaning.
- Missing values: count them, look at the rows, decide to drop, fill or investigate.
- Duplicates and impossible values.
- Distributions: summary table first, then plots.
- Outliers: flag them, explain them, delete only with a reason.
- Relationships: correlations, then group comparisons.
- Confounders: before you believe a group difference, check what else differs between the groups.
Plot these with Matplotlib, reshape with pandas, and when you are ready to predict mpg, continue to building a machine learning model with scikit-learn. Summary statistics for any column are also one click away in our descriptive statistics calculator.
Frequently asked questions
What is exploratory data analysis?
EDA is the first pass over a dataset: checking its structure, missing values, distributions and relationships so that you know what you have before you model or report anything.
What Python libraries are used for EDA?
pandas does most of the work, with Matplotlib or seaborn for charts. This tutorial used only pandas.
How do I handle missing values?
First find out why they are missing. If few and unrelated to anything else, as the 6 horsepower values here, dropping them is fine. Otherwise consider filling them or modelling the missingness.
Does a correlation mean one thing causes another?
No. Section 8 shows how a group difference can come from a third factor. Correlation is a reason to look closer, not a conclusion.
