Quick answer
Before trusting a dataset or fitting a model, check what each row represents, column types, units, missing values, duplicate identifiers and impossible values. Then inspect histograms, box plots and scatter plots, including meaningful subgroups. Investigate unusual records rather than automatically deleting them: a unit error needs correction; a genuine extreme may need to stay. NIST recommends understanding why outliers appeared before considering their removal. (itl.nist.gov)
1. Define the question and what one row represents
Exploratory data analysis, or EDA, helps you uncover structure, identify anomalies and examine assumptions before choosing a model. It is an investigative process, not simply a collection of attractive charts. (itl.nist.gov)
Start with a concrete question:
“What should we inspect before using delivery records to predict delivery duration?”
Write down the dataset’s grain—what one row represents—and a short data dictionary. For this tutorial, use these explicit definitions:
| Field | Meaning | Expected format |
|---|---|---|
delivery_id |
Identifier for one completed delivery | Unique, nonmissing text |
route |
Route category | urban or rural |
distance_km |
Route distance in kilometers | Positive number |
duration_min |
Minutes from dispatch to completion | Nonnegative number |
These are rules for the example, not universal delivery-industry standards. A real project needs definitions confirmed by its data provider.
Also ask:
- Does the extract contain all deliveries or only completed ones?
- Are canceled and unfinished deliveries recorded elsewhere?
- Were distance and route known when a prediction would be made?
- Does duration mean driving time, dispatch-to-completion time or something else?
For a predictive model, information unavailable at prediction time can cause data leakage: evaluation results look better than they should because the model received information it would not have in actual use. (scikit-learn.org)
2. Build a small example and inspect its structure
The following dataset is entirely synthetic. Its values are deliberately chosen for teaching; they are not company measurements or evidence about real delivery performance.
Use Python with pandas and Matplotlib installed. The API references for this tutorial are pandas 3.0.6 and Matplotlib 3.11.2. Record your installed versions when reproducing the example. (pandas.pydata.org)
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
print("pandas:", pd.__version__)
print("Matplotlib:", matplotlib.__version__)
raw = pd.DataFrame({
"delivery_id": [f"D{i:02d}" for i in range(1, 13)],
"route": [
"urban", "urban", "urban", "urban",
"urban", "urban", "rural", "rural",
"rural", "rural", "urban", "rural"
],
"distance_km": [2, 3, 4, 5, 6, 4, 10, 12, 14, 16, 3, 8],
"duration_min": [
18, 22, 25, 28, 1800, 95,
38, 42, 48, 55, -5, None
]
})
print(raw.dtypes)
print(raw.isna().sum())
print(raw[["distance_km", "duration_min"]].describe())
duplicates = raw[
raw.duplicated(subset=["delivery_id"], keep=False)
]
print("Rows with duplicate IDs:", len(duplicates))
For numeric columns, pandas describe() reports the nonmissing count, mean, standard deviation, minimum, quartiles and maximum. It excludes missing values, so the reported count is not necessarily the dataset’s row count. The duplicate check above examines identifiers and marks every member of a duplicate group. (pandas.pydata.org)
Expected checks for this example:
- 12 rows and no duplicate delivery identifiers;
- one missing duration;
- a minimum duration of −5;
- a maximum duration of 1,800.
Treat these as investigation prompts. An unusual maximum is not, by itself, proof of an error.
For your own data, add explicit checks for required columns, permitted category labels and missing identifiers. Do not assume that a successful file import means the contents meet your definitions.
3. Separate invalid records from legitimate extremes
This example includes a fictional audit record with three facts established by construction:
- D05: the value
1800was recorded in seconds but placed in a minutes column. Its correct duration is1800 / 60 = 30minutes. - D06: the 95-minute duration is genuine within the synthetic scenario; it represents a documented delay.
- D11: the negative duration is invalid under our elapsed-time definition, and no corrected value is available.
D12 has an unknown duration. Do not silently treat that as zero.
Preserve the original table, make a working copy and record each decision:
clean = raw.copy()
unit_error = clean["delivery_id"].eq("D05")
clean.loc[unit_error, "duration_min"] = (
clean.loc[unit_error, "duration_min"] / 60
)
invalid_duration = clean["duration_min"].lt(0)
missing_duration = clean["duration_min"].isna()
review = clean.loc[
invalid_duration | missing_duration
].copy()
analysis = clean.loc[
~invalid_duration & ~missing_duration
].copy()
assert len(raw) == len(analysis) + len(review)
assert analysis["delivery_id"].is_unique
assert analysis["duration_min"].ge(0).all()
assert analysis["distance_km"].gt(0).all()
The working analysis has 10 rows. Two remain in a review table: one invalid duration and one missing duration.
This is an exclusion from these duration charts, not permission to delete the records permanently. In a real project, retain the raw value, correction, evidence and reason for exclusion.
NIST emphasizes that unusual observations can reveal either recording problems or important features of the process being studied. Understand their origin before deciding what to do with them. (itl.nist.gov)
Common mistake: dividing every large duration by 60. A large number alone does not establish its unit. Without source evidence, mark it unresolved.
4. Use histograms to inspect the distribution
A histogram groups numeric values into intervals called bins. It helps reveal the distribution’s center, spread, asymmetry, multiple peaks and unusual values. (itl.nist.gov)
Compare the original and reviewed duration values:
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(raw["duration_min"].dropna(), bins=5)
axes[0].set_title("Original records")
axes[1].hist(analysis["duration_min"], bins=5)
axes[1].set_title("After documented review")
for ax in axes:
ax.set_xlabel("Delivery duration (minutes)")
ax.set_ylabel("Number of deliveries")
fig.tight_layout()
plt.show()
Matplotlib’s hist() computes and plots a histogram; specifying bins=5 requests five equal-width bins across the plotted range. (matplotlib.org)
Chart description: In the original plot, the 1,800-minute value stretches the horizontal scale, compressing the other observations into the leftmost bin. After the documented correction and exclusions, nine durations fall between 18 and 55 minutes, while one remains at 95 minutes. The two panels have different horizontal scales.
Try another bin count, such as four or eight. Use this as a practical sensitivity check: does your interpretation survive a different grouping of the same values? Bin boundaries are part of the histogram’s construction, not natural boundaries in the data. (itl.nist.gov)
With only 10 observations, describe the visible values rather than claiming to have established a population distribution. Do not force the data into a bell-shaped story merely because you plan to fit a model.
5. Use box plots to flag values for investigation
A box plot summarizes the median and quartiles. In Matplotlib’s default convention, the box runs from the first quartile, Q1, to the third quartile, Q3. Whiskers reach the most distant observations within 1.5 interquartile ranges of the box; observations beyond them appear separately. (matplotlib.org)
The interquartile range, or IQR, is:
IQR = Q3 − Q1
Lower fence = Q1 − 1.5 × IQR
Upper fence = Q3 + 1.5 × IQR
These fences provide a statistical flag, not a business-validity rule. (itl.nist.gov)
fig, ax = plt.subplots(figsize=(5, 4))
ax.boxplot(analysis["duration_min"], whis=1.5)
ax.set_xticks([1], ["Reviewed deliveries"])
ax.set_ylabel("Delivery duration (minutes)")
ax.set_title("Unusual does not mean invalid")
fig.tight_layout()
plt.show()
Chart description: The median is 34 minutes. The central half of the observations spans approximately 25.75 to 46.5 minutes. The 95-minute delivery appears above the upper whisker.
For these values, using pandas’ default linear quantile calculation:
- Q1 = 25.75;
- Q3 = 46.5;
- IQR = 20.75;
- upper fence = 77.625.
The 95-minute record exceeds that fence. Nevertheless, we retain it because the example establishes that it is genuine.
The useful conclusion is: “Investigate this delivery,” not “delete this delivery.” NIST likewise recommends investigating outliers before considering elimination. (itl.nist.gov)
6. Examine relationships and compare subgroups
A scatter plot displays paired numeric observations. It can reveal relationships, curvature, changing variability and points that are unusual relative to another variable. An observed association does not prove causation. (itl.nist.gov)
Plot distance against duration and distinguish routes using both marker shape and a legend:
fig, ax = plt.subplots(figsize=(7, 4))
for route, marker in [("urban", "o"), ("rural", "^")]:
group = analysis.loc[analysis["route"].eq(route)]
ax.scatter(
group["distance_km"],
group["duration_min"],
marker=marker,
label=route
)
delayed = analysis.loc[analysis["delivery_id"].eq("D06")]
ax.annotate(
"D06: documented delay",
xy=(
delayed["distance_km"].iloc[0],
delayed["duration_min"].iloc[0]
),
xytext=(6, 85),
arrowprops={"arrowstyle": "->"}
)
ax.set_xlabel("Route distance (km)")
ax.set_ylabel("Delivery duration (minutes)")
ax.legend(title="Route")
fig.tight_layout()
plt.show()
Matplotlib’s scatter() plots paired x and y values and supports configurable markers. (matplotlib.org)
Chart description: Five urban observations rise from 18 minutes at 2 kilometers to 30 minutes at 6 kilometers. A sixth urban delivery takes 95 minutes at 4 kilometers. Four rural observations rise from 38 minutes at 10 kilometers to 55 minutes at 16 kilometers.
Summarize each subgroup as well:
print(
analysis.groupby("route")["duration_min"]
.agg(["count", "median", "min", "max"])
)
Expected values:
| Route | Count | Median | Minimum | Maximum |
|---|---|---|---|---|
| Urban | 6 | 26.5 | 18 | 95 |
| Rural | 4 | 45 | 38 | 55 |
Do not conclude that the rural category causes longer deliveries. In this constructed dataset, rural routes also cover longer distances. Compare observations within groups and ask what other factors differ. NIST describes subgroup-conditioned scatter plots as a way to explore such structure. (itl.nist.gov)
For real data, repeat relevant comparisons by date, source system or service category. Always report group sizes alongside summaries.
7. Turn exploration into a documented readiness decision
Finish with a short decision log rather than a folder of unexplained charts.
For this example, the defensible summary is:
Twelve synthetic records were inspected. One verified unit error was corrected. One invalid duration and one missing duration were set aside for review. Ten records remain for duration analysis, including the genuine 95-minute delivery.
Before proceeding, ask:
- Definitions: Are grain, units and field meanings explicit?
- Integrity: Have identifier, category, range and missing-value checks been reviewed?
- Corrections: Can each change be traced to evidence?
- Charts: Are axes labeled with units, exclusions disclosed and unusual records visible?
- Subgroups: Are differences examined with group sizes and relevant context?
- Limitations: Is it clear which questions the data cannot answer?
For modeling, protect an independent test set from decisions about features and learned preprocessing. Fit scaling, imputation and other learned transformations using training data only; apply those fitted transformations consistently to later data. Scikit-learn recommends pipelines to help enforce this separation. (scikit-learn.org)
This tiny teaching dataset is an EDA exercise, not a meaningful model-evaluation benchmark. Its lesson is the workflow: check definitions, inspect values, visualize structure, investigate exceptions and document what remains uncertain.