# Exploratory Data Analysis in Python: A Step-by-Step Walkthrough

> Learn exploratory data analysis (EDA) in Python with pandas, seaborn and Matplotlib. Check types, missing values, impossible values, distributions, categories and correlations in a used-car dataset.

Source: https://www.pythoncharts.com/python/eda-python-walkthrough/ | Published: 2026-12-06 | Author: Alex Scott | Category: Python | Tags: eda, exploratory-data-analysis, pandas, seaborn, matplotlib, data-cleaning, correlation, distribution

Exploratory data analysis (EDA) in Python is a short loop: look at the structure with `df.shape`, `df.dtypes` and `df.describe()`, find missing and impossible values, plot each column, compare groups, then check how columns relate. The goal is to learn what is in the data before you model it. This walkthrough runs that loop on a simulated table of used-car listings, with a chart at most steps. It was run with pandas 3.1, seaborn 0.13.2 and Matplotlib 3.11.

## Quick Example

The data is 1,200 listings (seeded, so you get the same table). It has the problems real tables have: some missing mileage and fuel type, four listings priced at $1 and two with a mileage of 999,999. The chart answers four questions at once: how is price spread, what is missing, how does price move with age, and which columns move together.

```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Simulated listings for 1,200 used cars (seeded, so you get the same data)
rng = np.random.default_rng(17)
n = 1200
brand = rng.choice(["Toyota", "Honda", "Ford", "Kia", "BMW"], n, p=[0.28, 0.22, 0.22, 0.16, 0.12])
fuel = rng.choice(["petrol", "diesel", "hybrid", "electric"], n, p=[0.5, 0.25, 0.15, 0.1])
age = rng.integers(0, 16, n)
mileage = np.clip(age * rng.normal(11_000, 3_000, n) + rng.normal(2_000, 800, n), 300, None).round(-1)
base = pd.Series(brand).map({"Toyota": 24_000, "Honda": 23_000, "Ford": 21_000, "Kia": 19_500, "BMW": 36_000})
bump = pd.Series(fuel).map({"petrol": 1.0, "diesel": 1.04, "hybrid": 1.12, "electric": 1.3})
price = base * bump * np.exp(-0.11 * age - mileage / 600_000 + rng.normal(0, 0.09, n))
cars = pd.DataFrame({"brand": brand, "fuel": fuel, "age": age, "mileage": mileage, "price": price.round(-1)})

cars.loc[rng.choice(n, 70, replace=False), "mileage"] = np.nan      # missing mileage
cars.loc[rng.choice(n, 30, replace=False), "fuel"] = np.nan         # missing fuel type
cars.loc[[5, 211, 640, 990], "price"] = 1                           # placeholder prices
cars.loc[[88, 402], "mileage"] = 999_999                            # sentinel mileage

fig, axes = plt.subplots(2, 2, figsize=(11, 7.5))
sns.histplot(cars["price"], bins=40, ax=axes[0, 0], color="#4c78a8")
axes[0, 0].set(title="Price: how are values spread?", xlabel="Price ($)")
cars.isna().mean().mul(100).plot.barh(ax=axes[0, 1], color="#e45756")
axes[0, 1].set(title="Missing values (%)", xlabel="% of rows")
sns.boxplot(data=cars, x="age", y="price", ax=axes[1, 0], color="#72b7b2", fliersize=2)
axes[1, 0].set(title="Price by age: any pattern?", xlabel="Age (years)", ylabel="Price ($)")
sns.heatmap(cars.select_dtypes("number").corr(), annot=True, fmt=".2f", cmap="vlag", center=0, ax=axes[1, 1])
axes[1, 1].set(title="Correlation")
fig.tight_layout()
plt.show()
```

![Four panels: a right-skewed histogram of car prices, a bar chart showing 5.8 percent of mileage and 2.5 percent of fuel type missing, box plots of price falling with age, and a correlation heatmap with age and price at -0.86](https://www.pythoncharts.com/python/eda-python-walkthrough/images/eda-quick-example.png)

Four things stand out. Prices are right-skewed, with a small pile of values at $1 on the far left. Mileage is missing in 5.8% of rows and fuel type in 2.5%. Price drops steadily with age. And age and price have a correlation of -0.86. The $1 prices show up as the four dots at zero in the box plot panel, and the 999,999 mileages quietly distort the mileage correlations. The steps below take these in order.

## Step 1: Look at the shape, types and summary statistics

Start with `shape`, `dtypes` and `describe()`. You are checking that the number of rows is what you expect, that numbers are numbers and not strings, and that the min and max make sense:

```python
print(cars.shape)
print(cars.dtypes)
print(cars.describe().round(0))
```

```text
(1200, 5)
brand          str
fuel           str
age          int64
mileage    float64
price      float64
dtype: object
          age   mileage    price
count  1200.0    1130.0   1200.0
mean      7.0   86335.0  11439.0
std       5.0   68686.0   7455.0
min       0.0     620.0      1.0
25%       4.0   37798.0   5520.0
50%       7.0   76940.0   9385.0
75%      11.0  125022.0  15742.0
max      15.0  999999.0  44440.0
```

Two numbers look wrong. The minimum price is $1, and the maximum mileage is 999,999 on a table where the next-highest is under 300,000. `count` is 1,130 for mileage against 1,200 for the other numeric columns, so 70 values are missing (`df.info()` gives the same counts). The `str` dtype is what pandas 3 shows for text columns; older versions show `object`.

## Step 2: Find impossible values

Missing values are easy to spot. Placeholders and sentinels are harder, because they look like data. Filter for values that cannot be right, count them, and decide what to do with each. A $1 price is a placeholder, so those rows are dropped. 999,999 is a "no value" code, so it becomes `NaN`:

```python
print("price under $500:", (cars["price"] < 500).sum())
print("mileage over 500,000:", (cars["mileage"] > 500_000).sum())
print("duplicate rows:", cars.duplicated().sum())

clean = cars[cars["price"] >= 500].copy()
clean["mileage"] = clean["mileage"].where(clean["mileage"] < 500_000)
print(clean.shape)
print(cars[["age", "mileage", "price"]].corr().round(2).loc["price"].to_dict())
print(clean[["age", "mileage", "price"]].corr().round(2).loc["price"].to_dict())
```

```text
price under $500: 4
mileage over 500,000: 2
duplicate rows: 0
(1196, 5)
{'age': -0.86, 'mileage': -0.66, 'price': 1.0}
{'age': -0.86, 'mileage': -0.79, 'price': 1.0}
```

The last two lines show why this step matters. With the two 999,999 values in, price and mileage correlate at -0.66. Without them it is -0.79. Two bad rows out of 1,200 shifted the correlation by 0.13, and the correlation heatmap in the Quick Example was drawn from the uncleaned table. Run `clean.isna().sum()` afterwards to see what is still missing (72 mileages and 30 fuel types), and see [Visualize Missing Data in Python with missingno](https://www.pythoncharts.com/python/missing-data-plots-python/) for how to tell whether gaps are random. To flag unusual values that are not impossible, see [Outlier Plots in Python](https://www.pythoncharts.com/python/outlier-detection-plots-python/).

## Step 3: Plot each numeric column

Plot one column at a time before you plot any pairs. A histogram shows the shape, and the `kde=True` line smooths it. Use `countplot` for a column of whole numbers like age:

```python
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
sns.histplot(clean["price"], bins=40, kde=True, ax=axes[0], color="#4c78a8")
axes[0].set(title="Price", xlabel="Price ($)")
sns.histplot(clean["mileage"].dropna() / 1000, bins=40, kde=True, ax=axes[1], color="#f58518")
axes[1].set(title="Mileage", xlabel="Miles (thousands)")
sns.countplot(x=clean["age"], ax=axes[2], color="#54a24b")
axes[2].set(title="Age", xlabel="Age (years)", ylabel="Listings")
fig.tight_layout()
plt.show()
```

![Three panels: a right-skewed histogram of price with most cars under 20000 dollars, a histogram of mileage in thousands of miles with a spike near zero, and a bar chart of listings per age from 0 to 15 that is roughly flat](https://www.pythoncharts.com/python/eda-python-walkthrough/images/eda-distributions.png)

Price is right-skewed (skewness 1.26): the tallest bars sit between $4,000 and $6,000, with a thin tail past $30,000. Mileage is less skewed (0.52) and has a spike near zero, since about 7% of cars have under 10,000 miles. Age is close to flat, with between 58 and 93 listings in each year from 0 to 15. A skewed column like price is a hint to try a log scale or a log transform before fitting a linear model.

## Step 4: Compare categories

For a categorical column, count the rows in each group and compare a numeric column across groups. Sorting boxes by median (`order=`) makes the ranking readable. See [Seaborn Boxplot](https://www.pythoncharts.com/seaborn/seaborn-boxplot/) and [Seaborn Countplot](https://www.pythoncharts.com/seaborn/seaborn-countplot/) for more options:

```python
order = clean.groupby("brand")["price"].median().sort_values(ascending=False).index
fig, axes = plt.subplots(1, 2, figsize=(11, 4), gridspec_kw={"width_ratios": [3, 2]})
sns.boxplot(data=clean, x="brand", y="price", order=order, ax=axes[0], color="#b279a2")
axes[0].set(title="Price by brand", xlabel="", ylabel="Price ($)")
sns.countplot(data=clean, x="fuel", order=["petrol", "diesel", "hybrid", "electric"], ax=axes[1], color="#9d755d")
axes[1].set(title="Listings by fuel type", xlabel="", ylabel="Listings")
fig.tight_layout()
plt.show()
print(clean.groupby("brand")["price"].median().sort_values(ascending=False))
```

```text
brand
BMW       15640.0
Honda      9550.0
Toyota     9060.0
Ford       8310.0
Kia        7790.0
Name: price, dtype: float64
```

![Box plots of price by brand sorted by median, with BMW highest at about 15600 dollars and Kia lowest at about 7800, next to a bar chart of listings by fuel type with petrol far ahead of diesel, hybrid and electric](https://www.pythoncharts.com/python/eda-python-walkthrough/images/eda-categories.png)

BMW's median price ($15,640) is about twice Kia's ($7,790), and its box is the widest. Petrol dominates the listings (53%), followed by diesel (23%), hybrid (14%) and electric (10%). Rows with a missing fuel type drop out of the right panel. Groups this small can look different by chance, so look at the counts before reading much into a gap.

## Step 5
## Step 5: Check relationships

A scatter plot of two numeric columns, with a third variable as color, shows the shape of the relationship and whether groups separate. Price drops in a curve, not a line, so a log-scaled y-axis straightens it. For many numeric columns at once, [`sns.pairplot`](https://www.pythoncharts.com/seaborn/seaborn-pairplot/) draws every pair, and the [seaborn heatmap post](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/) covers the correlation matrix:

```python
fig, ax = plt.subplots(figsize=(8, 5))
plot_df = clean.dropna(subset=["fuel", "mileage"]).assign(miles_k=lambda d: d["mileage"] / 1000)
sns.scatterplot(data=plot_df, x="miles_k", y="price", hue="fuel",
                hue_order=["petrol", "diesel", "hybrid", "electric"], alpha=0.6, s=22, ax=ax)
ax.set(yscale="log", xlabel="Mileage (thousands)", ylabel="Price ($, log scale)", title="Price falls with mileage")
ax.set_yticks([3000, 5000, 10000, 20000, 40000], ["$3k", "$5k", "$10k", "$20k", "$40k"])
ax.minorticks_off()
plt.show()
```

![Scatter plot of price on a log scale against mileage in thousands, points colored by fuel type, falling from about 20000 dollars at zero miles to about 3000 at 250000 miles with the fuel types mixed together](https://www.pythoncharts.com/python/eda-python-walkthrough/images/eda-price-mileage.png)

On the log scale the cloud is close to a straight downward band: price falls by a steady percentage per mile. The fuel colors are mixed together, so this chart can't say whether fuel type matters. That is what the next step is for. Overplotting is also a problem at about 1,100 points, so `alpha=0.6` lets dense areas show.

## Step 6
## Step 6: Check a pattern is not a side effect

Before believing a difference between groups, ask whether another column explains it. Electric cars here could look pricier only because they are newer. Restricting to cars aged 3 to 6 keeps age roughly constant:

```python
same_age = clean[clean["age"].between(3, 6)]
by_fuel = same_age.groupby("fuel")["price"].agg(["median", "count"]).sort_values("median")
print(by_fuel)

fig, ax = plt.subplots(figsize=(7, 3.6))
ax.barh(by_fuel.index, by_fuel["median"], color="#4c78a8")
ax.set(xlabel="Median price ($), cars aged 3 to 6", title="Fuel type premium at a similar age")
plt.show()
```

```text
           median  count
fuel                    
diesel    12880.0     64
petrol    13160.0    162
hybrid    14100.0     35
electric  15805.0     36
```

![Horizontal bar chart of median price for cars aged 3 to 6 by fuel type: electric about 15800 dollars, hybrid 14100, petrol 13160 and diesel 12880](https://www.pythoncharts.com/python/eda-python-walkthrough/images/eda-fuel-premium.png)

The premium survives: among cars aged 3 to 6, electric listings have a median price of $15,805, against $13,160 for petrol. Hybrid and electric each have only 35 or 36 cars in this slice, so treat the size of the gap as approximate. Checking for confounders like this is the step that keeps EDA findings from turning into wrong conclusions. Here the simulated data was built with a fuel premium, so this check confirms it. In real data you would get a less tidy answer and would follow up with a regression.

## Which chart answers which EDA question?

| Question | Chart | Code |
|---|---|---|
| How is a numeric column spread? | Histogram | `sns.histplot(df["x"], kde=True)` |
| What is missing? | Bar of `isna().mean()` | `df.isna().mean().plot.barh()` |
| Are there impossible values? | `describe()`, then filters | `df[df["x"] < limit]` |
| How do groups differ? | Box plot | `sns.boxplot(data=df, x="g", y="x")` |
| How many in each group? | Count plot | `sns.countplot(data=df, x="g")` |
| Do two columns move together? | Scatter plot | `sns.scatterplot(data=df, x="a", y="b", hue="g")` |
| Which columns move together? | Correlation heatmap | `sns.heatmap(df.corr(numeric_only=True), annot=True)` |

## Practical Tips

- **Clean before you correlate.** Two sentinel values moved a correlation from -0.79 to -0.66 in this table. Do the impossible-value check before any summary that uses means or correlations.
- **Keep the raw table.** Make a cleaned copy with `.copy()` and write down each change, so you can explain what was dropped and why.
- **Check `describe()` min and max first.** Values like 0, -1, 999 and 9999 are usually codes, not data.
- **Correlation measures straight-line relationships only.** A strongly curved relationship, like price against age here, can show a weaker correlation than its real strength. Plot it.
- **Look at one column, then two, then three.** Plotting everything at once with `sns.pairplot` is fine for a first look, but each step above answers a question the pair grid can't.

## Similar Topics

- [Visualize Missing Data in Python with missingno](https://www.pythoncharts.com/python/missing-data-plots-python/)
- [Outlier Plots in Python](https://www.pythoncharts.com/python/outlier-detection-plots-python/)
- [Seaborn Pairplot](https://www.pythoncharts.com/seaborn/seaborn-pairplot/)
