100 Exercises / Machine Learning / Practical Machine Learning 100 Exercises
Manufacturing Data Analysis in Python: From CSV Loading to Correlations
Inspect factory CSV data with Python: check types and missing values, summarize production, and explore distributions, scatter plots, and correlations.
Before factory data can support meetings or improvement work, check what each column means, which values are missing, and how the records should be aggregated. This article uses synthetic daily records from a precision parts factory to work through CSV loading, summary statistics, distributions, scatter plots, and correlations.
The 100 Machine Learning Exercises series covers data inspection, preprocessing, regression and classification, validation, feature engineering, forecasting, anomaly detection, recommendations, clustering, and MLOps. Each exercise connects a practical question to a calculation and explains what the result can tell us. This article covers No.001–No.010.
[!NOTE] This material is adapted, with permission, from notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama. All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.
Introduction: Practical Challenges in Manufacturing Covered in This Article
The question is which production line, product, or equipment conditions to investigate after a recent rise in defects. The daily CSV contains production quantity, downtime, temperature, vibration, and defect counts. Check column definitions, missing values, and distributions before calculating averages or fitting models; input errors and changes in product mix can otherwise look like equipment problems.
The goal is an initial data report that helps decide which equipment records to inspect and what additional measurements to collect. Correlations help prioritize hypotheses; they do not establish causes.
Common situations on site
- Multiple lines of daily reports were consolidated, but the units, input rules, and reasons for missing data were not aligned.
- Only the average for all factories is shared, making product composition and line differences invisible.
- The relationship between heuristic rules and data, such as ‘defects are common on hot days,’ remains unverified.
- Definitions of downtime and quantity of good products differ between analysts and on-site operators
Why is this issue so difficult to judge?
Defect rates can change with product mix, production line, lot, and inspection conditions as well as equipment settings. Missing measurements may also be systematic: if vibration readings disappear during shutdowns, dropping those rows could hide abnormal operation. Check the observation unit, data types, missing values, distributions, and differences between groups.
Exercises in this article
| No. | operation | Practical Confirmation Items |
|---|---|---|
| 001 | Loading CSV | Encoding, delimiter, and observation unit |
| 002 | First rows, last rows, and columns | Date range, ordering, and required columns |
| 003 | Number of rows and columns | Observation Coverage and Granularity |
| 004 | data type | Whether calculation and time series processing are possible |
| 005 | missing value | Scale of Missed Measurements and Operational Reasons |
| 006 | basic statistics | Level, variation, anomaly candidates |
| 007 | Category Aggregation | Differences in line and product mix |
| 008 | Histogram | Distribution shape, tails, multiple groups |
| 009 | Scatter plot | Relationships between variables and differences between groups |
| 010 | correlation coefficient | Prioritizing hypotheses |
Preparing the Python environment
Run each article from top to bottom in a fresh Jupyter kernel, including collapsed setup cells. [IN: n] and [OUT: n] identify matching input and output. The displayed results were rerun; library versions can affect numbers or formatting even with the same random seed.
Use pandas for tables, numpy to generate synthetic data, and matplotlib for plots. A fixed random seed makes repeated runs reproducible in the same software environment.
from IPython.display import display
from io import StringIO
import sys
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
SEED = 1201
rng = np.random.default_rng(SEED)
plt.rcParams["figure.figsize"] = (8, 4.5)
print(f"Python: {sys.version.split()[0]}")
print(f"pandas: {pd.__version__}")
print(f"matplotlib: {matplotlib.__version__}")
print(f"random number seed: {SEED}")
Python: 3.14.4
pandas: 3.0.3
matplotlib: 3.11.0
random number seed: 1201
Creating the synthetic data
Each row represents one production line on one date, with one product assigned to that line for the day. Define this unit before aggregating: totals mean different things when rows represent machines, lots, or time intervals.
The defect rate is defined by the following formula.
The synthetic data makes defects somewhat more likely as temperature, vibration, and downtime increase, and gives product P-300 a higher defect risk. A few vibration readings are deliberately removed.
Show setup code (run this cell)
n_days = 60
dates = pd.date_range("2025-04-01", periods=n_days, freq="D")
lines = np.array(["L-A", "L-B", "L-C"])
products = np.array(["P-100", "P-200", "P-300"])
records = []
for date in dates:
for line in lines:
product = rng.choice(products, p=[0.45, 0.35, 0.20])
planned = int(rng.integers(430, 571))
downtime = max(0, rng.gamma(2.0, 8.0) + (line == "L-C") * 6)
produced = max(300, int(planned - 1.25 * downtime + rng.normal(0, 10)))
temperature = rng.normal(72 + (line == "L-C") * 2.5, 3.5)
vibration = rng.normal(2.6 + (line == "L-B") * 0.20, 0.38)
defect_rate = (
0.010
+ 0.0006 * downtime
+ 0.0018 * (temperature - 72)
+ 0.009 * (vibration - 2.6)
+ 0.010 * (product == "P-300")
)
defect_rate = float(np.clip(defect_rate, 0.002, 0.12))
defects = int(rng.binomial(produced, defect_rate))
records.append(
[
date,
line,
product,
planned,
produced,
downtime,
temperature,
vibration,
defects,
]
)
source_df = pd.DataFrame(
records,
columns=[
"date",
"line",
"product",
"planned_qty",
"produced_qty",
"downtime_min",
"temperature_c",
"vibration_mm_s",
"defect_qty",
],
)
source_df.loc[rng.choice(source_df.index, 7, replace=False), "vibration_mm_s"] = np.nan
source_df["defect_rate_pct"] = source_df["defect_qty"] / source_df["produced_qty"] * 100
source_df["downtime_min"] = source_df["downtime_min"].round(1)
source_df["temperature_c"] = source_df["temperature_c"].round(1)
source_df["vibration_mm_s"] = source_df["vibration_mm_s"].round(2)
source_df["defect_rate_pct"] = source_df["defect_rate_pct"].round(2)
# Create CSV strings in memory to avoid dependencies on external files
csv_buffer = StringIO()
source_df.to_csv(csv_buffer, index=False)
print(f"Created Fictional Data: {len(source_df):,}rows × {source_df.shape[1]}columns")
source_df.head(3)
Created Fictional Data: 180rows × 10columns
| date | line | product | planned_qty | produced_qty | downtime_min | temperature_c | vibration_mm_s | defect_qty | defect_rate_pct | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2025-04-01 | L-A | P-100 | 431 | 412 | 13.1 | 78.9 | 2.42 | 22 | 5.34 |
| 1 | 2025-04-01 | L-B | P-100 | 457 | 435 | 17.7 | 72.1 | 3.18 | 11 | 2.53 |
| 2 | 2025-04-01 | L-C | P-200 | 460 | 421 | 16.7 | 74.8 | 2.57 | 9 | 2.14 |
No.001: Loading CSV
Practical purpose
Loading a CSV is the first data acceptance check. Verify the observation unit, encoding, delimiter, dates, and required columns, not just whether the file opens.
Method
Read the in-memory CSV with pd.read_csv and parse the date column with parse_dates. Keeping loading separate from analysis makes it easier to replace this example with a file or database source.
Check with Python
csv_buffer.seek(0)
df = pd.read_csv(csv_buffer, parse_dates=["date"])
print(f"Loading complete: {len(df):,}rows × {df.shape[1]}columns")
df.head(3)
Loading complete: 180rows × 10columns
| date | line | product | planned_qty | produced_qty | downtime_min | temperature_c | vibration_mm_s | defect_qty | defect_rate_pct | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2025-04-01 | L-A | P-100 | 431 | 412 | 13.1 | 78.9 | 2.42 | 22 | 5.34 |
| 1 | 2025-04-01 | L-B | P-100 | 457 | 435 | 17.7 | 72.1 | 3.18 | 11 | 2.53 |
| 2 | 2025-04-01 | L-C | P-200 | 460 | 421 | 16.7 | 74.8 | 2.57 | 9 | 2.14 |
Interpreting the results
The CSV contains 180 rows with production, equipment, and quality fields. In production, compare the columns and row count with the input specification to detect upstream changes.
No.002: Checking the beginning, end, and column names of the data
Practical purpose
The first and last rows can reveal an incorrect date range or ordering. Compare column names with the data dictionary.
Method
Use head, tail, and columns together. The endpoints cannot reveal every missing record or ordering error in the middle; additional checks must cover all rows.
Check with Python
print("list by name:", df.columns.tolist())
print("\nLead2rows")
display(df.head(2))
print("end2rows")
display(df.tail(2))
list by name: ['date', 'line', 'product', 'planned_qty', 'produced_qty', 'downtime_min', 'temperature_c', 'vibration_mm_s', 'defect_qty', 'defect_rate_pct']
Lead2rows
| date | line | product | planned_qty | produced_qty | downtime_min | temperature_c | vibration_mm_s | defect_qty | defect_rate_pct | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2025-04-01 | L-A | P-100 | 431 | 412 | 13.1 | 78.9 | 2.42 | 22 | 5.34 |
| 1 | 2025-04-01 | L-B | P-100 | 457 | 435 | 17.7 | 72.1 | 3.18 | 11 | 2.53 |
end2rows
| date | line | product | planned_qty | produced_qty | downtime_min | temperature_c | vibration_mm_s | defect_qty | defect_rate_pct | |
|---|---|---|---|---|---|---|---|---|---|---|
| 178 | 2025-05-30 | L-B | P-200 | 455 | 430 | 10.3 | 77.8 | 3.25 | 10 | 2.33 |
| 179 | 2025-05-30 | L-C | P-200 | 460 | 435 | 12.9 | 73.0 | 2.82 | 8 | 1.84 |
Interpreting the results
The displayed dates run from April 1 to May 30, 2025. Check the full ordering with df["date"].is_monotonic_increasing and compare the column set with the required fields.
No.003: Checking the Number of Rows and Columns in the Data
Practical purpose
For 60 days and three lines, expect 180 rows. Missing submissions or duplicate records can change aggregates before any model is fitted.
Method
Use shape to check rows and columns, then count duplicate date–line keys. Compare the observed keys with the operating calendar when checking complete coverage.
Check with Python
expected_rows = n_days * len(lines)
actual_rows, actual_cols = df.shape
duplicate_keys = df.duplicated(["date", "line"]).sum()
print(f"Achievements: {actual_rows}rows × {actual_cols}columns")
print(f"Difference from Expected Number of Lines: {actual_rows - expected_rows:+d}rows")
print(f"Date×line overlap: {duplicate_keys}rows")
Achievements: 180rows × 10columns
Difference from Expected Number of Lines: +0rows
Date×line overlap: 0rows
Interpreting the results
Both the row-count difference and duplicate-key count are zero. This alone does not prove that every expected date–line combination is present: an unexpected key could replace a missing one. Check the actual key set against the expected set.
No.004: Checking Data Types
Practical purpose
Numeric quantities and dates need appropriate types for arithmetic and time-based aggregation. Strings can otherwise concatenate or fail to support date operations.
Method
Use dtypes and notna().sum() to inspect types and non-missing counts. Expect datetime dates, string identifiers, and numeric measurements. String columns may appear as str, string, or object, depending on the pandas version and loading method.
Check with Python
dtype_table = pd.DataFrame(
{"dtype": df.dtypes.astype(str), "non_null": df.notna().sum()}
)
display(dtype_table)
print(f"dateRows are date-based: {pd.api.types.is_datetime64_any_dtype(df['date'])}")
| dtype | non_null | |
|---|---|---|
| date | datetime64[us] | 180 |
| line | str | 180 |
| product | str | 180 |
| planned_qty | int64 | 180 |
| produced_qty | int64 | 180 |
| downtime_min | float64 | 180 |
| temperature_c | float64 | 180 |
| vibration_mm_s | float64 | 173 |
| defect_qty | int64 | 180 |
| defect_rate_pct | float64 | 180 |
dateRows are date-based: True
Interpreting the results
Dates are datetime values, quantities are integers, and continuous measurements are floating-point values. Vibration has fewer non-missing records, which will need attention in the next exercise.
No.005: Check for missing values
Practical purpose
A missing sensor reading may indicate communication loss, calibration, or a shutdown. Investigate the reason before replacing it with zero or dropping the row.
Method
For column , calculate the missing count and percentage , where is the total row count. Different analyses may therefore use different numbers of observations.
Check with Python
missing = pd.DataFrame(
{
"missing_count": df.isna().sum(),
"missing_rate_pct": df.isna().mean().mul(100).round(2),
}
)
missing = missing.query("missing_count > 0")
display(missing if not missing.empty else pd.DataFrame({"status": ["No missing"]}))
| missing_count | missing_rate_pct | |
|---|---|---|
| vibration_mm_s | 7 | 3.89 |
Interpreting the results
Seven vibration readings are missing, about 3.9% of the rows. Check whether they concentrate on particular lines or during long downtime. This article leaves them missing and uses available observations for plots and correlations.
No.006: Checking Basic Statistics
Practical purpose
An average can hide unusual downtime or variability. Review medians, quartiles, minima, and maxima as well.
Method
describe returns counts, means, standard deviations, and quantiles. Standard deviations carry the units of their variables, so their sizes cannot be compared directly across different measurements.
Check with Python
numeric_cols = [
"produced_qty",
"downtime_min",
"temperature_c",
"vibration_mm_s",
"defect_rate_pct",
]
stats = df[numeric_cols].describe().T.round(2)
display(stats)
print(f"Median defect rate: {df['defect_rate_pct'].median():.2f}%")
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| produced_qty | 180.0 | 474.74 | 40.42 | 372.00 | 444.00 | 474.00 | 508.00 | 574.00 |
| downtime_min | 180.0 | 19.11 | 11.63 | 1.40 | 10.30 | 17.95 | 26.02 | 63.10 |
| temperature_c | 180.0 | 72.89 | 3.72 | 59.10 | 70.70 | 73.00 | 75.30 | 81.00 |
| vibration_mm_s | 173.0 | 2.64 | 0.41 | 1.69 | 2.36 | 2.63 | 2.91 | 3.81 |
| defect_rate_pct | 180.0 | 2.55 | 1.38 | 0.00 | 1.53 | 2.37 | 3.29 | 6.11 |
Median defect rate: 2.37%
Interpreting the results
Compare maxima with the upper quartiles to identify days for investigation. A maximum above the third quartile does not by itself establish a long right tail; check the histogram before making that claim.
No.007: Aggregating Categorical Variables
Practical purpose
Changes in the product mix can move the overall defect rate even without a change in equipment performance. Compare counts and quality measures by line and product.
Method
Use groupby to summarize each line. Calculate the combined defect rate as total defective units divided by total produced units, rather than an unweighted average of daily percentages.
Check with Python
line_summary = df.groupby("line", as_index=False).agg(
records=("date", "size"),
produced_qty=("produced_qty", "sum"),
defect_qty=("defect_qty", "sum"),
avg_downtime_min=("downtime_min", "mean"),
)
line_summary["weighted_defect_rate_pct"] = (
line_summary["defect_qty"] / line_summary["produced_qty"] * 100
)
display(line_summary.round(2))
print("Number of Cases by Product:")
display(df["product"].value_counts().rename_axis("product").to_frame("records"))
| line | records | produced_qty | defect_qty | avg_downtime_min | weighted_defect_rate_pct | |
|---|---|---|---|---|---|---|
| 0 | L-A | 60 | 28345 | 638 | 16.64 | 2.25 |
| 1 | L-B | 60 | 28781 | 665 | 18.37 | 2.31 |
| 2 | L-C | 60 | 28327 | 854 | 22.31 | 3.01 |
Number of Cases by Product:
| records | |
|---|---|
| product | |
| P-100 | 82 |
| P-200 | 56 |
| P-300 | 42 |
Interpreting the results
Each line contributes 60 records. Line C has higher average downtime and a higher production-weighted defect rate. Check product mix and operating conditions before assigning a cause.
No.008: Visualizing Numerical Variables with Histograms
Practical purpose
A histogram shows tails, multiple peaks, and concentration near operational limits that an average can conceal.
Method
Divide defect rates into bins and count observations in each bin. Compare several bin settings or use a box plot when the shape is unclear. Mark the mean and median for reference.
Check with Python
fig, ax = plt.subplots()
ax.hist(df["defect_rate_pct"], bins=14, color="#2878B5", edgecolor="white", alpha=0.85)
ax.axvline(df["defect_rate_pct"].mean(), color="#D95319", linestyle="--", label="Mean")
ax.axvline(
df["defect_rate_pct"].median(), color="#2CA02C", linestyle=":", label="Median"
)
ax.set_title("Distribution of Daily Defect Rate")
ax.set_xlabel("Defect rate (%)")
ax.set_ylabel("Number of line-days")
ax.grid(axis="y", alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()

Interpreting the results
Most daily defect rates are low, with a tail to the right. Reporting the median and upper quantiles alongside the mean makes the effect of a few high-defect days easier to explain.
No.009: Viewing Relationships Between Variables in Scatter Plots
Practical purpose
A relationship between downtime and defects gives the team a reason to investigate setup changes, restarts, or equipment problems. Color by line to distinguish group differences.
Method
Each point represents one production line on one day. Plot downtime horizontally and defect rate vertically, and look for curvature, changing spread, and unusual observations.
Check with Python
fig, ax = plt.subplots()
colors = {"L-A": "#2878B5", "L-B": "#F39C12", "L-C": "#3A923A"}
for line, part in df.groupby("line"):
ax.scatter(
part["downtime_min"],
part["defect_rate_pct"],
s=35,
alpha=0.7,
label=line,
color=colors[line],
)
ax.set_title("Downtime and Daily Defect Rate by Line")
ax.set_xlabel("Downtime (minutes)")
ax.set_ylabel("Defect rate (%)")
ax.grid(alpha=0.3)
ax.legend(title="Line")
plt.tight_layout()
plt.show()

Interpreting the results
Higher downtime is associated with higher defect rates, and line C has more points toward the upper right. Product mix or other variables may influence both, so the plot does not establish that downtime causes defects.
No.010: Checking the Correlation Coefficient
Practical purpose
Correlations help prioritize pairs of measurements for investigation. They do not prove causation or fully describe nonlinear relationships.
Method
Pearson correlation is . It lies between -1 and 1 when both variables have nonzero variance. pandas excludes missing values separately for each pair, so sample sizes can differ.
Check with Python
corr_cols = [
"produced_qty",
"downtime_min",
"temperature_c",
"vibration_mm_s",
"defect_rate_pct",
]
corr = df[corr_cols].corr().round(2)
display(corr)
fig, ax = plt.subplots(figsize=(7, 5.5))
im = ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
ax.set_xticks(range(len(corr_cols)), corr_cols, rotation=35, ha="right")
ax.set_yticks(range(len(corr_cols)), corr_cols)
for i in range(len(corr_cols)):
for j in range(len(corr_cols)):
ax.text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center", va="center", fontsize=9)
ax.set_title("Pearson Correlation Matrix")
ax.set_xlabel("Variables")
ax.set_ylabel("Variables")
ax.grid(False)
fig.colorbar(im, ax=ax, label="Correlation coefficient")
plt.tight_layout()
plt.show()
| produced_qty | downtime_min | temperature_c | vibration_mm_s | defect_rate_pct | |
|---|---|---|---|---|---|
| produced_qty | 1.00 | -0.20 | -0.18 | 0.04 | -0.23 |
| downtime_min | -0.20 | 1.00 | 0.13 | -0.03 | 0.60 |
| temperature_c | -0.18 | 0.13 | 1.00 | -0.08 | 0.57 |
| vibration_mm_s | 0.04 | -0.03 | -0.08 | 1.00 | 0.13 |
| defect_rate_pct | -0.23 | 0.60 | 0.57 | 0.13 | 1.00 |

Interpreting the results
Defect rate correlates positively with downtime and temperature and negatively with production quantity. These relationships agree with the synthetic data design. Follow-up analysis should account for product and line differences and use time-aware validation.
What the results mean in practice
In this initial diagnosis, the number of data entries and key granularity were as expected, there were a few missing vibration values, and the stop time and defect rate of line C were relatively high. Also, since the defect rate is not symmetrical, not only the average but also the median and upper quantiles should be used together.
These results suggest checking maintenance history, product mix, changeovers, work teams, and sensor calibration. They do not establish that line C causes defects or that reducing downtime will necessarily improve quality. Inspecting missing values and group differences helps select model inputs and follow-up investigations.
Requirements for deployment
- Data dictionary: Document what one row represents, each unit and calculation, and the department responsible for the data.
- Automatic Acceptance Inspection: Check required columns, type, number of entries, duplicates, value range, and freshness
- Missing Reason Code: Distinguishing between communication outages, maintenance, downtime, and input gaps
- Grouping variables: Make lines, products, equipment, work teams, and lots traceable.
- Rules of Judgment: Decide who decides to investigate, stop, and improve at what threshold
- Effectiveness Verification: Evaluate before and after improvement under comparable conditions for the same KPI
If personal information or trade secrets are involved, access control, anonymization, retention periods, and audit logs are also included in the design. Instead of directly running the exploratory results in the notebook, we move them to processes that include regular execution, exception notifications, and version management.
Conclusion
From No.001 to No.010, we loaded the CSV and checked structure, type, missing data, statistics, category composition, distribution, and relationships between variables. By following this order, you can reduce input errors and aggregation illusions, and explain “what additional checks should be made” before moving on to machine learning.
Next, investigate missing vibration readings, compare relationships within each line and product, and check maintenance histories. Share column definitions and findings with the factory team before choosing further analyses.
Consulting for businesses
At Surikobo, we support everything from inventory of manufacturing data, design of quality and equipment KPIs, PoC, construction of predictive and anomaly detection models, to on-site implementation, tailored to your challenges and data maturity. You can consult from stages such as “We have data, but where should we check?” or “Analysis results don’t lead to improvement activities.”
📩 Contact Us: www.surikobo.co.jp/contact
Please feel free to consult us first.