All articles →

100 Exercises / Python / 100 Python Exercises for Data Analysis

Python Setup and Basics: Start Analyzing Production Data

Learn Python setup, Jupyter cells, printing, comments, and errors, then summarize and plot fictional production, defect, and utilization data.

100 Python Exercises for Data Analysis

Learn Python for data analysis through 100 exercises based on manufacturing tasks. The series is intended for manufacturing and digital-transformation staff.

About this material These notebooks were used in corporate training by Surikobo or its representative, Hiroshi Wayama, and were adapted for publication with permission. All data are fictional and do not represent actual company or factory results.


Purpose of the series

Manufacturing teams record production counts, defective units, and equipment utilization each day. This series shows how to read, summarize, and plot these data in Python. Each exercise uses a short example so you can check the output as you learn.


Composition of 10 chapters

ChapterTitleExerciseMain Topic
Chapter 1Python preparation and basicsNo.001~010Execution environment, print, how to read errors, flow of analysis
Chapter 2Variables, types, and operationsNo.011-020Numerical values, character strings, Boolean values, four arithmetic operations, and comparison operations
Chapter 3Strings, lists, and dictionariesNo.021-030Basics of string operations, lists, and dictionaries
Chapter 4Conditional branching and repetitionNo.031-040if statements, for statements, while statements, and rank determination
Chapter 5Functions, modules, and exception handlingNo.041-050Function definitions, standard libraries, try-except
Chapter 6File operations and CSVNo.051-060File reading/writing/CSV operations/Monthly aggregation
Chapter 7Introduction to NumPyNo.061-070Array operations, statistical calculations, and condition extraction
Chapter 8Introduction to PolarsNo.071~080Series/DataFrame/CSV reading
Chapter 9Data processing using PolarsNo.081-090Column operations, missing value processing, sorting, and duplicate removal
Chapter 10Aggregation/Visualization/Mini analysisNo.091~100group_by/Matplotlib/Correlation/Analysis report

About this chapter

This notebook is Chapter 1 (No.001–010). It uses fictional Q1 2024 production data from an automotive-parts factory’s third line. Allow about 60 minutes to set up Python and try the basic syntax. The examples use NumPy and Matplotlib and need no external data files.


100 Exercises Chapter 1 (No.001 to No.010): Python preparation and basics

Data on production volume, defect rate, and equipment utilization rate continues to accumulate at the manufacturing site. “We have data, but we are not using it.” In order to solve such on-site issues, This is the first chapter of 100 Exercises on learning Python from scratch.

This article covers the following 10 exercises.

No.Title
001Understand what you can do with Python
002Organizing the reasons why Python is used in data analysis
003Preparing the Python execution environment
004Understand the basic operations of Jupyter Notebook
005Run a Python script
006Displaying characters with the print function
007Write a comment
008Understanding how to read error displays
009Executing code cells separately
010Understand the basic flow of data analysis

Target audience: Manufacturing industry personnel and DX promotion personnel with no Python experience Time required: Approximately 60 minutes Libraries used: NumPy, Matplotlib (no external data required)

Example task

Overview of target factories/issues

The example concerns the third production line at an automotive metal-parts factory with 200 employees. Daily production, defective-unit counts, and equipment utilization are entered in Excel. A staff member compiles charts at month-end, leaving little time to investigate changes as they happen.

Common situations in the field

SituationActual problem
Data is managed in ExcelThere are so many sheets that it takes 1 to 2 hours to aggregate
Monthly reports are done manuallyProne to human error
It is too late to notice changes in the defect rateMonth-end tabulation does not allow countermeasures to be taken in time for the following month
Equipment maintenance is “repair after it breaks”Large opportunity loss due to failure to perform preventive maintenance
Absence of person in charge of analysisIssues accumulate without anyone learning Python

In all of these situations, you have the data, you’re motivated, but you can’t do anything about it. You can change this by simply learning the basics of Python.

Common mistakes

Dilemma of “tool selection” and “learning cost”

When starting Python, it can be hard to choose learning materials, set up an environment, or connect examples to daily work. This chapter starts with displaying manufacturing data and calculating simple summaries. Run one small task at a time and check how the code produces its result before moving on to machine learning or dashboards.

Exercises in this chapter

Position of Chapter 1

Chapter 1 (this time): Python preparation and basics ← here
Chapter 2: Variables, types, and operations
Chapter 3: Strings, Lists, and Dictionaries
Chapter 4: Conditional branching and repetition
Chapter 5: Functions, Modules, and Exception Handling
Chapter 6: File operations and CSV
Chapter 7: Introduction to NumPy
Chapter 8: Introduction to Polars
Chapter 9: Data processing with Polars
Chapter 10: Aggregation/Visualization/Mini-analysis

Learning roadmap for No.001~010

[No.001-002] Get an overview of Python
      ↓
[No.003-004] Prepare the environment and start using Jupyter
      ↓
[No.005-006] Write and run the first code
      ↓
[No.007-008] Get into the habit of writing code correctly
      ↓
[No.009-010] Divide the code and get the overall picture of the analysis

In No.010, you will apply what you have learned so far to experience actual data analysis flow on a manufacturing line.

Preparing the Python environment

Execution environment

Run cells in order from the top. Outputs are examples; the OS, versions, and file paths vary by environment. The setup cells import libraries and configure random data and plotting.

This notebook has been confirmed to work in the following environments.

[IN: 1]
import platform

print(platform.platform())
[OUT: 1]
macOS-26.5.2-arm64-arm-64bit-Mach-O
[IN: 2]
import sys

print(f"Python {sys.version.split()[0]}")
[OUT: 2]
Python 3.14.4

Import the libraries and configure the plot display.

Setup: Imports and display settings (expand)
[IN: 3]
%matplotlib inline
%config InlineBackend.figure_format = 'svg'

import random
import sys
import platform

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

# Fixed random number seed (ensuring reproducibility)
seed = 42
random.seed(seed)
np.random.seed(seed)

# Japanese font settings
if platform.system() == 'Darwin':
    matplotlib.rcParams['font.family'] = 'Hiragino Maru Gothic Pro'
elif platform.system() == 'Linux':
    matplotlib.rcParams['font.family'] = 'IPAGothic'
matplotlib.rcParams['axes.unicode_minus'] = False

print(f"Python     : {sys.version.split()[0]}")
print(f"NumPy      : {np.__version__}")
print(f"Matplotlib : {matplotlib.__version__}")
print(f"OS         : {platform.system()} {platform.release()}")
[OUT: 3]
Python     : 3.14.4
NumPy      : 2.5.1
Matplotlib : 3.11.0
OS         : Darwin 25.5.0

Creating the sample data

Data background

In this article, we will introduce the Q1 2024 (January to March, 91 days) of Automotive parts factory 3rd line. The production data are fictional. All data is generated on the fly in Python (no external files required).

Variable nameContentUnit
productionDaily productionUnits
defectsNumber of defective items by daypcs
defect_rate_pctDaily defect rate%
operation_rateDaily equipment utilization rate%

These data are used in No.010. No.009 generates a separate six-day example. No.001 to 008 are code examples for each exercise alone.

Setup: Generate the sample data (expand)
[IN: 4]
# Fictional data: Auto parts factory 3rd line 2024 Q1 production results
np.random.seed(42)

n_days = 91  # 2024 Q1 (January to March)
day_index = np.arange(1, n_days + 1)

# Daily production count (target 1,000 units/day, normal noise with SD 80, clipped to 750–1,200 units)
production = (1000 + np.random.normal(0, 80, n_days)).astype(int)
production = np.clip(production, 750, 1200)

# Defect rate (monthly cycle trend + Gaussian noise)
true_defect_rate = 0.020 + 0.008 * np.sin(day_index * 2 * np.pi / 30)
defects = np.round(production * true_defect_rate + np.random.normal(0, 2, n_days)).astype(int)
defects = np.clip(defects, 0, production // 10)
defect_rate_pct = defects / production * 100

# Equipment utilization rate (%)
operation_rate = 94 - 2 * np.cos(day_index * 2 * np.pi / 30) + np.random.normal(0, 1.5, n_days)
operation_rate = np.clip(operation_rate, 82, 99)

print("Overview of fictitious data")
print("=" * 45)
print(f"  period       : 2024yearQ1({n_days}days)")
print(f"  Total production count   : {production.sum():>8,} units")
print(f"  Total number of defective items : {defects.sum():>8,} units")
print(f"  Average defect rate : {defect_rate_pct.mean():>8.2f} %")
print(f"  Average equipment utilization rate : {operation_rate.mean():>8.1f} %")
[OUT: 4]
Overview of fictitious data
=============================================
  period       : 2024yearQ1(91days)
  Total production count   :   90,250 units
  Total number of defective items :    1,824 units
  Average defect rate :     2.01 %
  Average equipment utilization rate :     94.0 %

No.001: Understand what you can do with Python

Use in practice

Think about how Python could help with your own tasks, such as summarizing daily reports or drawing charts. This series focuses on automating repeated work and examining patterns in data.

Approach

Work through four steps: load sensor and manually entered data; inspect missing values, outliers, and inconsistent formats; summarize and visualize the data; then use the results for monitoring, prediction, optimization, or reports. Python can automate repeated steps in this workflow.

Check with Python

Categorize and list the problems that Python can solve in the manufacturing industry.

[IN: 5]
# No.001: Understand what you can do with Python

categories = {
    "Data collection and maintenance": [
        "Load and combine CSV/Excel files",
        "Real-time acquisition of sensor data",
        "Connection/query with database (SQL)",
    ],
    "Aggregation/statistical analysis": [
        "Daily/monthly tally of production counts and defect rates",
        "Correlation analysis between processes",
        "Automatic creation of control charts (Xbar-R control charts)",
    ],
    "Prediction/machine learning": [
        "Detection of signs of defective products",
        "Predictive maintenance (PdM) of equipment",
        "Optimization of production planning through demand forecasting",
    ],
    "Automation/Reporting": [
        "Automatic generation and email of daily reports",
        "Building a web dashboard",
        "API integration with Manufacturing Execution System (MES)",
    ],
}

print("Categories of manufacturing problems that can be solved with Python")
print("=" * 55)
total = 0
for category, items in categories.items():
    print(f"\n▶ {category}")
    for item in items:
        print(f"   ・{item}")
        total += 1
print(f"\nTotal: {total} Usage example")
[OUT: 5]
Categories of manufacturing problems that can be solved with Python
=======================================================

▶ Data collection and maintenance
   ・Load and combine CSV/Excel files
   ・Real-time acquisition of sensor data
   ・Connection/query with database (SQL)

▶ Aggregation/statistical analysis
   ・Daily/monthly tally of production counts and defect rates
   ・Correlation analysis between processes
   ・Automatic creation of control charts (Xbar-R control charts)

▶ Prediction/machine learning
   ・Detection of signs of defective products
   ・Predictive maintenance (PdM) of equipment
   ・Optimization of production planning through demand forecasting

▶ Automation/Reporting
   ・Automatic generation and email of daily reports
   ・Building a web dashboard
   ・API integration with Manufacturing Execution System (MES)

Total: 12 Usage example

Interpreting the results

The list covers data collection, summaries, charts, prediction, and automation. Start with a task whose results are easy to check, such as summarizing an existing Excel file. The time saved depends on the data size, the task, and the environment.


No.002: Organize the reasons why Python is used in data analysis

Use in practice

A proposal to introduce Python should explain how it fits the task and existing tools. Comparing the available options helps colleagues and managers decide which combination to use.

Approach

Excel supports reviewing tables, summarizing smaller datasets, and sharing results. SQL handles database queries and aggregation; R supports statistical analysis; Python supports tasks from data preparation to integration with other systems. Their uses overlap, so choose a combination that fits the workflow.

Check with Python

Displays the characteristics of each tool in a comparative table format.

[IN: 6]
# Typical uses overlap; suitability depends on the task and data.
tool_uses = [
    ("Excel", "Review and edit tables; share summaries"),
    ("SQL", "Query, filter, and aggregate database records"),
    ("R", "Statistical analysis, model evaluation, and plots"),
    ("Python", "Prepare data, summarize it, schedule tasks, and connect systems"),
]

for tool, use in tool_uses:
    print(f"{tool:<8}: {use}")

print("\nUses overlap. Choose a combination that fits the data and workflow.")
[OUT: 6]
Excel   : Review and edit tables; share summaries
SQL     : Query, filter, and aggregate database records
R       : Statistical analysis, model evaluation, and plots
Python  : Prepare data, summarize it, schedule tasks, and connect systems

Uses overlap. Choose a combination that fits the data and workflow.

Interpreting the results

Python lets you save loading, cleaning, summarizing, and plotting as one repeatable workflow. The same steps can then be applied to the next month’s data. Excel performance depends on formulas, formatting, and hardware as well as row count. You can keep Excel for data entry and review while using Python for repeated calculations.


No.003: Prepare the Python execution environment

Use in practice

Environment setup can interrupt learning before the first analysis runs. Agreeing on a Python environment makes results easier to reproduce and the code easier to hand over.

Approach

Record the Python version and library dependencies, using tools such as pyenv, conda, requirements.txt, or pyproject.toml as appropriate. Create a separate venv or Conda environment for each project to reduce dependency conflicts.

Check with Python

Check information about your current Python environment.

[IN: 7]
# No.003: Check the Python execution environment

import sys
import platform
import importlib.metadata as meta

print("=== Checking the Python execution environment ===")
print(f"Python version  : {sys.version.split()[0]}")
print(f"OS                 : {platform.system()} {platform.release()}")
print(f"Python execution path    : {sys.executable}")
print()

# Checking the version of installed libraries
key_libs = ["numpy", "matplotlib", "polars", "scipy"]
print("Main library versions:")
for lib in key_libs:
    try:
        ver = meta.version(lib)
        print(f"  {lib:<15}: {ver}")
    except meta.PackageNotFoundError:
        print(f"  {lib:<15}: Not installed")
[OUT: 7]
=== Checking the Python execution environment ===
Python version  : 3.14.4
OS                 : Darwin 25.5.0
Python execution path    : /Users/hiroshi/private/kobo/notebook/.venv/bin/python

Main library versions:
  numpy          : 2.5.1
  matplotlib     : 3.11.0
  polars         : 1.42.1
  scipy          : 1.18.0

Interpreting the results

The Python version and execution path shown in the output is This is information that must be included in the environmental specifications shared by the team.

Most of the problems are “It’s the same code but it doesn’t work on my machine” This is due to version differences. Create requirements.txt at the start of the project, Get into the habit of arranging your environment with pip install -r requirements.txt.

Notes on installation: When installing Python on a Windows PC at the manufacturing site, pip may not be available due to security policy. Please coordinate with your IT department in advance to find out how to use it in an offline environment.


No.004: Understand the basic operations of Jupyter Notebook

Use in practice

Jupyter Notebook keeps code, results, and explanations together. It is useful for analysis reports, sharing a procedure, and developing a prototype while checking each step. Reproducing results also requires the same inputs, dependencies, and execution order.

Approach

Jupyter Notebook is useful for running small pieces of code and checking the results. When a task needs scheduled execution or integration with another system, you can move the processing code into a .py file. Choose the format that fits the task.

Check with Python

Check frequently used shortcuts and cell types.

[IN: 8]
# No.004: Basic operations of Jupyter Notebook

# List of frequently used keyboard shortcuts
shortcuts = {
    "Shift + Enter": "Execute cell and move to next cell",
    "Ctrl + Enter": "Run a cell and stay in the same cell",
    "Esc → A": "Add new cell above current cell",
    "Esc → B": "Add new cell below current cell",
    "Esc → M": "Convert code cells to Markdown cells",
    "Esc → Y": "Convert Markdown cells to code cells",
    "Esc → DD": "delete cell",
    "Esc → Z": "Restore deleted cells",
    "Ctrl + Shift + -": "Split cells at cursor position",
}

print("Jupyter Notebook frequently used shortcuts")
print("=" * 58)
for key, desc in shortcuts.items():
    print(f"  {key:<24} → {desc}")

print()
print("cell type")
print("-" * 45)
cell_types = {
    "Code cell": "Write and run Python code",
    "Markdown cell": "Write explanatory text, formulas, and tables",
    "Raw cell": "Text to be output as is during conversion",
}
for t, desc in cell_types.items():
    print(f"  {t:<16}: {desc}")
[OUT: 8]
Jupyter Notebook frequently used shortcuts
==========================================================
  Shift + Enter            → Execute cell and move to next cell
  Ctrl + Enter             → Run a cell and stay in the same cell
  Esc → A                  → Add new cell above current cell
  Esc → B                  → Add new cell below current cell
  Esc → M                  → Convert code cells to Markdown cells
  Esc → Y                  → Convert Markdown cells to code cells
  Esc → DD                 → delete cell
  Esc → Z                  → Restore deleted cells
  Ctrl + Shift + -         → Split cells at cursor position

cell type
---------------------------------------------
  Code cell       : Write and run Python code
  Markdown cell   : Write explanatory text, formulas, and tables
  Raw cell        : Text to be output as is during conversion

Interpreting the results

Memorizing shortcuts drastically reduces mouse operations and speeds up analysis. In particular, Shift + Enter (Run and Next) is the most frequently used shortcut.

Jupyter Notebooks can be converted directly to HTML or PDF and shared as reports. If you are creating periodic reports for your manufacturing industry manually, Moving to Automatic report generation with Python + Jupyter will save you a lot of time.


No.005: Execute Python script

Use in practice

A Python script (.py) is useful for scheduled processing. For example, a script can summarize the previous day’s production at 8 a.m. and prepare a report. A scheduler such as cron or Task Scheduler can run it regularly.

Approach

Organize the usage of Notebooks and Scripts.

UsesAppropriate tools
Trial and error/exploratory analysisJupyter Notebook
Regular execution/automationPython script (.py)
Report generationConvert with Jupyter → nbconvert
Production system integrationPython script

Check with Python

Check the basic structure of the script and an example output of production results.

[IN: 9]
# No.005: Execute Python script

# ---- Assumed structure of the production script (daily_report.py) ----
# import library
# → Data loading
# → Data processing
# → Aggregation/calculation
# → Output/save results

# ---- Execute the same process directly here ----

# Definition of data
line_name = "3rd line"
date_str = "2024-03-31"
target_production = 1000
actual_production = 985
defects_count = 18

# calculation
achievement_rate = actual_production / target_production * 100
defect_rate = defects_count / actual_production * 100

# Output of results
print("=" * 42)
print("Daily production performance report")
print(f"  date       : {date_str}")
print(f"  line name   : {line_name}")
print("=" * 42)
print(f"  Target production count : {target_production:>6,} units")
print(f"  Actual production count : {actual_production:>6,} units")
print(f"  Achievement rate     : {achievement_rate:>6.1f} %")
print(f"  Number of defective products   : {defects_count:>6,} units")
print(f"  Defect rate     : {defect_rate:>6.2f} %")
print("=" * 42)
[OUT: 9]
==========================================
Daily production performance report
  date       : 2024-03-31
  line name   : 3rd line
==========================================
  Target production count :  1,000 units
  Actual production count :    985 units
  Achievement rate     :   98.5 %
  Number of defective products   :     18 units
  Defect rate     :   1.83 %
==========================================

Interpreting the results

If you write a script that automatically generates output like this, You no longer have to manually create reports every morning.

Points for practical deployment: To periodically execute a script on the server, For Linux, use cron, for Windows, use “Task Scheduler”. Ultimately, by linking notifications to Slack and Teams, You can create a system in which you will be notified immediately if there is an abnormality.


No.006: Displaying characters with the print function

Use in practice

Use print() to inspect values and show processing progress. A message after loading sensor data helps you see which steps finished before an error occurred.

Approach

Knowing how to use print will be useful in the following situations.

  • Check process progress: print("Data loading completed...")
  • Confirm variable contents (debug): print(f"Defect rate={rate:.2f}%")
  • Warning/alert log output: Conditionally display warning messages

Check with Python

Check out the different ways to use the print function.

[IN: 10]
# No.006: Displaying characters with the print function

# basic display
print("Production line monitoring system started")

# Embedding variables and strings (f-string)
equipment_id = "EQP-023"
status = "Normal operation"
temperature = 74.5
print(f"equipmentID: {equipment_id} | status: {status} | temperature: {temperature}°C")

# Specifying the delimiter (sep) and end character (end)
lines_list = ["cutting line", "welding line", "assembly line", "inspection line"]
print("Lines in operation:", end=" ")
print(*lines_list, sep=" / ")

# Progress display of processing flow
for step in ["Data loading", "Pretreatment", "tally", "graph output"]:
    print(f"  [{step}]", end=" → ")
print("Completed")

# Formatting numbers
print()
total = 952
bad = 15
rate = bad / total * 100
print(f"Today's production count : {total:,} units")  # 3 digit comma separated
print(f"Number of defective products     : {bad} units")
print(f"Defect rate       : {rate:.2f}%")  # 2 decimal places
[OUT: 10]
Production line monitoring system started
equipmentID: EQP-023 | status: Normal operation | temperature: 74.5°C
Lines in operation: cutting line / welding line / assembly line / inspection line
  [Data loading] →   [Pretreatment] →   [tally] →   [graph output] → Completed

Today's production count : 952 units
Number of defective products     : 15 units
Defect rate       : 1.58%

Interpreting the results

f-string (f"...") allows you to embed variables in strings. It saves you the hassle of type conversion and concatenation, making your code easier to read.

In particular, format specifiers like {rate:.2f} are Be sure to remember this, as it frequently appears when outputting reports and formatting numbers.

Format specifierMeaningExample
:.2f2 decimal places3.14
:,3 digits separated by commas1,000,000
:>10Right alignment (width 10) 42
:<10Left alignment (width 10)42

No.007: Write a comment

Use in practice

Comments help colleagues understand code and help the original author return to it later. Explain assumptions, units, and reasons for decisions so that reviews and handovers do not depend on one person’s memory.

Approach

Use comments to explain a variable’s meaning or unit, or why a step is needed. For example, # Defect rate (%) = defective units / total production * 100 explains the calculation. # Skip division when production is zero on a nonworking day explains why a condition is needed.

Check with Python

Compare good and bad examples of how to write comments.

[IN: 11]
# No.007: Write a comment

# ---- Code without comments (hard to understand) ----
d = 15
t = 952
r = d / t * 100
print(f"[No comments] r = {r:.2f}")

print()

# ---- Code with comments (recommended) ----

# Today's number of defective products (unit: pieces) *Add the suffix _day to distinguish it from global variables
defects_day = 15

# Today's total production quantity (unit: units)
total_day = 952

# Defect rate calculation (in %)
# Definition: Defect rate = number of defective items / total number of production × 100
defect_rate_pct_val = defects_day / total_day * 100

# Warning judgment
# - Defect rate 5.0% or more: ALERT (consider immediate suspension)
# - Defect rate 2.0% or more: WARNING (report to administrator)
# - Defect rate less than 2.0%: OK (normal operation)
if defect_rate_pct_val >= 5.0:
    label = "[ALERT] Immediate action required"
elif defect_rate_pct_val >= 2.0:
    label = "[WARNING] Warning line exceeded"
else:
    label = "[OK] Within normal range"

print(f"{label}  Defect rate: {defect_rate_pct_val:.2f}%")
[OUT: 11]
[No comments] r = 1.58

[OK] Within normal range  Defect rate: 1.58%

Interpreting the results

The uncommented code (variable names d, t, r) works, but When I read it again a few months later, I don’t understand what was being calculated.

Commented code tells the reader “Why are we doing this calculation?”

Suggestions for team development: When using IT in the manufacturing industry, there are often only a few people who can write code. Inheriting code is a big risk. Developing the habit of commenting from the beginning protects your organization’s code assets.


No.008: Understand how to read error displays

Use in practice

An error message helps identify what failed and where. Common examples include text mixed into a numeric CSV column, division by zero on a day with no production, and inconsistent date formats. Read the error type and message before deciding what to fix.

Approach

Let’s identify three error patterns that are commonly encountered in manufacturing data.

Error typeCause exampleCorrective action
NameErrorTypographical error in variable name/used before definitionCheck spelling/review definition order
TypeErrorOperations on strings and numbers, etc.Type conversion with int() / float()
ZeroDivisionErrorCalculate the defect rate on the day when production quantity = 0Conditional branch with if total > 0:

Check with Python

Check out common errors and their workaround codes.

[IN: 12]
# No.008: Understand how to read error displays

print("=== Common errors and solutions ===\n")

# Error example 1: NameError
print("[Example of NameError]")
print("  >>> print(production_count)")
print("  NameError: name 'production_count' is not defined")
print("→ Misspelled variable name or \n used before definition")

# Error example 2: TypeError
print("[TypeError example]")
print('>>> "Defect rate: " + 1.57')
print("  TypeError: can only concatenate str (not 'float') to str")
print("→ Convert with str(1.57) or use f-string \n")

# Error example 3: ZeroDivisionError
print("[Example of ZeroDivisionError]")
print("  >>> 15 / 0")
print("  ZeroDivisionError: division by zero")
print("→ Exclude days when production quantity = 0 (holidays/equipment stoppages) using conditional branching \n")

# Example of addressed code
print("=== ZeroDivisionError handling example ===")
test_cases = [
    (952, 15),  # normal day
    (0, 0),  # Holidays (no production)
    (500, 25),  # half working day
]
for total, def_cnt in test_cases:
    if total > 0:
        rate = def_cnt / total * 100
        print(f"  Production count {total:>4} stand → Defect rate {rate:.2f}%")
    else:
        print(f"  Production count {total:>4} stand → No production (skip calculation)")
[OUT: 12]
=== Common errors and solutions ===

[Example of NameError]
  >>> print(production_count)
  NameError: name 'production_count' is not defined
→ Misspelled variable name or
 used before definition
[TypeError example]
>>> "Defect rate: " + 1.57
  TypeError: can only concatenate str (not 'float') to str
→ Convert with str(1.57) or use f-string

[Example of ZeroDivisionError]
  >>> 15 / 0
  ZeroDivisionError: division by zero
→ Exclude days when production quantity = 0 (holidays/equipment stoppages) using conditional branching

=== ZeroDivisionError handling example ===
  Production count  952 stand → Defect rate 1.58%
  Production count    0 stand → No production (skip calculation)
  Production count  500 stand → Defect rate 5.00%

Interpreting the results

Error messages are read as a set of three: line number, error type, and explanation. In particular, ZeroDivisionError appears frequently in manufacturing data.

  • Production quantity = 0 on holidays and equipment shutdown days, so it is essential to check the conditions in advance.
  • Instead of “Ignore the error and then move on” The idea of “designing data preprocessing that does not cause errors” is Significantly improves the quality of production data processing.

No.009: Execute code cells separately

Use in practice

Split a notebook into cells for loading, cleaning, summarizing, and plotting data. This makes problems easier to locate and the workflow easier to share. When an earlier step changes, rerun the later cells that depend on it.

Approach

This section provides design guidelines for the division of roles among cells.

[Cell 1] Import library (run only once)
[Cell 2] Define and read data
[Cell 3] Preprocessing (missing removal, type conversion, abnormal value removal)
[Cell 4] Aggregation/calculation
[Cell 5] Visualization/Graph creation
[Cell 6] Summary/output of results

Check with Python

Process production data for a hypothetical week step by step.

[IN: 13]
# No.009 - Cell 1: Data definition (library has been loaded at the beginning)

# 1 week production data (Monday to Saturday)
days_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
productions_week = [980, 1020, 1005, 990, 1015, 850]
defects_week = [18, 22, 15, 19, 17, 12]

print("Step 1: Define data Done")
print(f"  period: {len(days_week)} days")
print(f"  Total production quantity: {sum(productions_week):,} units")
[OUT: 13]
Step 1: Define data Done
  period: 6 days
  Total production quantity: 5,860 units
[IN: 14]
# No.009 - Cell 2: Aggregation/Calculation

# Defect rate calculation
defect_rates_week = [d / p * 100 for d, p in zip(defects_week, productions_week)]

print("Step 2: Aggregation/calculation completed")
print()
print(f"{'day of the week':<6} {'Production count':>8} {'Number of defective products':>8} {'Defect rate':>8}")
print("-" * 36)
for day, prod, bad, rate in zip(days_week, productions_week, defects_week, defect_rates_week):
    flag = "←Warning" if rate >= 2.0 else ""
    print(f"{day:<6} {prod:>8,} {bad:>8} {rate:>7.2f}%{flag}")
[OUT: 14]
Step 2: Aggregation/calculation completed

day of the week Production count Number of defective products Defect rate
------------------------------------
Monday      980       18    1.84%
Tuesday    1,020       22    2.16%←Warning
Wednesday    1,005       15    1.49%
Thursday      990       19    1.92%
Friday    1,015       17    1.67%
Saturday      850       12    1.41%
[IN: 15]
# No.009 - Cell 3: Visualization

fig, ax = plt.subplots(figsize=(9, 4))
bars = ax.bar(days_week, defect_rates_week, color="steelblue", edgecolor="white", alpha=0.85)

# Color-coded bars that exceed the warning line
for bar, rate in zip(bars, defect_rates_week):
    if rate >= 2.0:
        bar.set_color("tomato")

ax.axhline(y=2.0, color="orange", linestyle="--", linewidth=1.5, label="Warning line 2.0%")
ax.set_title("1 week defect rate trend (3rd line)", fontsize=13)
ax.set_xlabel("day of the week")
ax.set_ylabel("Defect rate (%)")
ax.legend()
ax.grid(True, axis="y", alpha=0.3)
plt.tight_layout()
plt.show()

print("Step 3: Graph output completed")
[OUT: 15]

1 week defect rate trend (3rd line)

Step 3: Graph output completed

Interpreting the results

Tuesday’s defect rate is 2.16%, at or above the 2.0% warning threshold, so its bar is red. Thursday is 1.92% and does not trigger a warning under this rule.

To change only the chart’s appearance, edit and rerun the third input cell in No.009. If you change the data or a calculation, rerun the affected later cells too. Giving each cell a clear purpose and explanation makes the notebook easier to hand over.


No.010: Understand the basic flow of data analysis

Use in practice

Start by deciding what you want to find out, then inspect, summarize, and plot the data. Here we check production against its target, defect rates, and equipment utilization, then identify questions that need more information.

Approach

Data analysis in the manufacturing industry will be easier to organize if you think about it along the lines of CRISP-DM.

1. Business understanding: Define what you want to solve
       ↓
2. Data understanding: Understand the quantity, quality, and structure of the data at hand
       ↓
3. Data preparation: Perform missing/outlier/type conversion/combining
       ↓
4. Modeling: Apply aggregation, statistics, and machine learning models
       ↓
5. Evaluation: Check whether the results are useful for on-site issues
       ↓
6. Deployment: Incorporate into regular reports, dashboards, and automatic notifications

This time, we will use everything we learned in No.001~009, Create a Mini Analysis Report to analyze the fictitious 3rd line 2024 Q1 data.

Check with Python

[IN: 16]
# No.010 - Step 1: Confirm the data (the fictitious data has been created at the beginning)

print("=== Step 1: Check data ===")
print(f"  period       : 2024yearQ1({n_days}days)")
print(f"  Total production count   : {production.sum():>8,} units")
print(f"  Total number of defective items : {defects.sum():>8,} units")
print(f"  Average defect rate : {defect_rate_pct.mean():>8.2f} %")
print(f"  Average equipment utilization rate : {operation_rate.mean():>8.1f} %")
print()

# Check basic statistics
print(f"{'indicators':<16} {'Production quantity (units)':>12} {'Defect rate (%)':>12} {'Equipment utilization rate (%)':>12}")
print("-" * 55)
stats_rows = [
    ("maximum value", production.max(), defect_rate_pct.max(), operation_rate.max()),
    ("minimum value", production.min(), defect_rate_pct.min(), operation_rate.min()),
    ("average value", production.mean(), defect_rate_pct.mean(), operation_rate.mean()),
    ("standard deviation", production.std(), defect_rate_pct.std(), operation_rate.std()),
]
for label, p, d, o in stats_rows:
    print(f"{label:<16} {p:>12.1f} {d:>12.2f} {o:>12.2f}")
[OUT: 16]
=== Step 1: Check data ===
  period       : 2024yearQ1(91days)
  Total production count   :   90,250 units
  Total number of defective items :    1,824 units
  Average defect rate :     2.01 %
  Average equipment utilization rate :     94.0 %

indicators       Production quantity (units) Defect rate (%) Equipment utilization rate (%)
-------------------------------------------------------
maximum value          1148.0         3.10        98.52
minimum value           790.0         0.83        89.76
average value           991.8         2.01        93.99
standard deviation         74.0         0.58         2.03
[IN: 17]
# No.010 - Step 2: Monthly tally of defect rate and operating rate

# Monthly slice (January: 0-30, February: 31-59, March: 60-90)
monthly_splits = [(0, 31, "January"), (31, 60, "February"), (60, 91, "March")]

# Number of days above warning line
high_defect_days = int((defect_rate_pct >= 2.0).sum())
alert_days = int((defect_rate_pct >= 3.0).sum())

print("=== Step 2: Aggregation of defect rate ===")
print(f"  Warning line (2%or more) Excess: {high_defect_days:>3} days / {n_days} during the day ({high_defect_days/n_days*100:.1f}%)")
print(f"  Alert line (3%above): {alert_days:>3} days / {n_days} during the day ({alert_days/n_days*100:.1f}%)")
print()

print(f"{'month':<6} {'Production count':>10} {'Number of defective products':>10} {'Defect rate':>10} {'equipment utilization rate':>10}")
print("-" * 50)
for s, e, label in monthly_splits:
    mp = production[s:e].sum()
    md_val = defects[s:e].sum()
    mr = md_val / mp * 100
    mo = operation_rate[s:e].mean()
    print(f"{label:<6} {mp:>10,} {md_val:>10,} {mr:>9.2f}% {mo:>9.1f}%")
[OUT: 17]
=== Step 2: Aggregation of defect rate ===
  Warning line (2%or more) Excess:  49 days / 91 during the day (53.8%)
  Alert line (3%above):   2 days / 91 during the day (2.2%)

month  Production count Number of defective products Defect rate equipment utilization rate
--------------------------------------------------
January     30,484        614      2.01%      94.2%
February     28,741        568      1.98%      94.0%
March      31,025        642      2.07%      93.8%
[IN: 18]
# No.010 - Step 3: Time series graph (3 panels)

fig, axes = plt.subplots(3, 1, figsize=(12, 11))

# ---- Graph 1: Trends in daily production ----
axes[0].plot(day_index, production, color="steelblue", linewidth=1.5, alpha=0.85, label="Actual production count")
axes[0].axhline(y=1000, color="crimson", linestyle="--", linewidth=1.5, label="Target (1,000 units)")
axes[0].fill_between(
    day_index, production, 1000, where=(production < 1000), alpha=0.15, color="crimson", label="Goal unachieved zone"
)
axes[0].set_title("Trends in daily production (Q1 2024 / 3rd line)", fontsize=13)
axes[0].set_xlabel("Number of days elapsed (days)")
axes[0].set_ylabel("Production quantity (units)")
axes[0].legend(fontsize=10)
axes[0].grid(True, alpha=0.3)

# ---- Graph 2: Trends in defect rate ----
axes[1].plot(day_index, defect_rate_pct, color="tomato", linewidth=1.5, alpha=0.85)
axes[1].axhline(y=2.0, color="orange", linestyle="--", linewidth=1.5, label="Warning line 2.0%")
axes[1].axhline(y=3.0, color="crimson", linestyle="--", linewidth=1.5, label="Alert line 3.0%")
axes[1].fill_between(
    day_index, defect_rate_pct, 3.0, where=(defect_rate_pct > 3.0), alpha=0.2, color="crimson", label="alert zone"
)
axes[1].set_title("Daily defect rate trends (2024 Q1/3rd line)", fontsize=13)
axes[1].set_xlabel("Number of days elapsed (days)")
axes[1].set_ylabel("Defect rate (%)")
axes[1].legend(fontsize=10)
axes[1].grid(True, alpha=0.3)

# ---- Graph 3: Distribution of equipment utilization rate (histogram) ----
axes[2].hist(operation_rate, bins=20, color="seagreen", edgecolor="white", alpha=0.85)
axes[2].axvline(
    x=float(operation_rate.mean()),
    color="crimson",
    linestyle="--",
    linewidth=1.5,
    label=f"average value: {operation_rate.mean():.1f}%",
)
axes[2].axvline(x=95.0, color="orange", linestyle=":", linewidth=1.5, label="Target equipment utilization rate: 95%")
axes[2].set_title("Distribution of equipment utilization rate (2024 Q1 / 3rd line)", fontsize=13)
axes[2].set_xlabel("Equipment utilization rate (%)")
axes[2].set_ylabel("Number of days (days)")
axes[2].legend(fontsize=10)
axes[2].grid(True, alpha=0.3)

plt.tight_layout()
plt.show()
[OUT: 18]

Trends in daily production (Q1 2024 / 3rd line); Daily defect rate trends (2024 Q1/3rd line); Distribution of equipment utilization rate (2024 Q1 / 3rd line)

[IN: 19]
# Monthly rate = total defects / total production, not the mean of daily rates.
# No.010 - Step 4: Monthly comparison graph

months = ["January", "February", "March"]
splits = [(0, 31), (31, 60), (60, 91)]
monthly_defect_rate_avg = [defects[s:e].sum() / production[s:e].sum() * 100 for s, e in splits]
monthly_op_rate_avg = [operation_rate[s:e].mean() for s, e in splits]
bar_colors = ["steelblue", "tomato", "seagreen"]

fig, axes = plt.subplots(1, 2, figsize=(11, 4))

# Monthly average defect rate
axes[0].bar(months, monthly_defect_rate_avg, color=bar_colors, edgecolor="white", alpha=0.85)
axes[0].axhline(y=2.0, color="orange", linestyle="--", linewidth=1.5, label="warning line")
for i, v in enumerate(monthly_defect_rate_avg):
    axes[0].text(i, v + 0.03, f"{v:.2f}%", ha="center", fontsize=11, fontweight="bold")
axes[0].set_title("Monthly defect rate (pooled, Q1 2024)", fontsize=13)
axes[0].set_xlabel("Month")
axes[0].set_ylabel("Defect rate (%)")
axes[0].legend()
axes[0].grid(True, axis="y", alpha=0.3)

# Monthly average capacity utilization rate
axes[1].bar(months, monthly_op_rate_avg, color=bar_colors, edgecolor="white", alpha=0.85)
axes[1].axhline(y=95.0, color="orange", linestyle="--", linewidth=1.5, label="Target equipment utilization rate 95%")
for i, v in enumerate(monthly_op_rate_avg):
    axes[1].text(i, v + 0.05, f"{v:.1f}%", ha="center", fontsize=11, fontweight="bold")
axes[1].set_title("Monthly average facility utilization rate (Q1 2024)", fontsize=13)
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Average equipment utilization rate (%)")
axes[1].legend()
axes[1].grid(True, axis="y", alpha=0.3)

plt.tight_layout()
plt.show()
[OUT: 19]

Monthly defect rate (pooled, Q1 2024); Monthly average facility utilization rate (Q1 2024)

Interpreting the results

Production is below the 1,000-unit target on 49 of 91 days (53.8%). Total production is 90,250 units.

Monthly defect rates, calculated as total defects divided by total production, are 2.01% in January, 1.98% in February, and 2.07% in March. January and March meet or exceed the 2.0% warning threshold. These pooled rates differ from simple means of daily rates.

Equipment utilization averages 93.99% over the period, below the 95% target. Monthly means are 94.2%, 94.0%, and 93.8%.

These data were generated randomly. Charts alone cannot establish causes such as equipment shutdowns or tool wear. For real data, compare the results with daily reports and maintenance records. With consistent input formats and date ranges, the same code can summarize the following month.


Applying the exercises at work

The first ten exercises introduce the following practical habits.

1. “Introduction” is directly connected to issues at the manufacturing site

Basic operations such as printing values and writing comments already help with production logs and code handovers.

2. Errors are not “walls” but “information”

ZeroDivisionError means a calculation tried to divide by zero. NameError means a name is not defined. Check the relevant line and its input data rather than assuming the cause from the error type alone.

3. Cell division is “documentation of analysis flow”

Separate loading, preparation, aggregation, and plotting into cells and add an explanation to each. Before sharing the notebook, restart the kernel and run all cells in order to check that the results can be reproduced.

4. Connect the steps in ten exercises

No.010 brings data inspection, aggregation, and visualization together. Repeating this workflow gives context to the language features introduced in later chapters.

Applying the code to your data

In order to implement the contents of Chapter 1 into the actual manufacturing site, the following steps are required.

Step 1: Prepare the environment

WorkContents
Installing PythonAnaconda or pyenv + venv
Introduction to Jupyterpip install jupyter or JupyterLab
Unify librariesAlign your team environment with requirements.txt
Check execution privilegesCheck company security policy (especially in Windows environment)

Step 2: Connect with existing data

  • CSV files: Python’s csv module and Polars (covered in Chapters 6 and 8).
  • Excel files: libraries such as openpyxl (outside this series).
  • Database connections: libraries such as sqlalchemy and pyodbc.

Step 3: Design the analysis cycle

Decide when to run the analysis and how to report results. Start with regular summaries and charts, then consider prediction or machine learning when the task and data justify them.

Step 4: Knowledge sharing within the organization

  • Manage analysis code with Git (GitHub, GitLab)
  • Create rules to share Jupyter Notebooks within your team
  • Maintain an environment where “anyone can run code written by someone”

Summary

Chapter 1 (No.001–010) introduced Python through fictional production-line data.

Review of what you learned

No.TitleKey points for use in the manufacturing industry
001Understand what you can do with PythonUnderstand the overall picture of DX
002Why Python is used for data analysisOrganizing the basis for tool selection
003Prepare the execution environmentUnify the environment as a team
004Basic operations of Jupyter NotebookUse for automatic generation of analysis reports
005Executing scriptsCreating a foundation for regular execution and automation
006Displaying characters with the print functionUsed for log output and status confirmation
007Write a commentLeave code inheritance materials
008How to read error displaysDetect data quality problems early
009Execute code cells separatelyDesign analysis flow step by step
010Basic flow of data analysisQ1 Experience the overall analysis of production results

Next steps

Chapter 2 (No.011–020) introduces variables, types, and operators through calculations involving quantities, unit prices, yields, and production targets.

Training and analysis support


Surikobo provides Python training and data analysis support for manufacturing industry and DX promotion staff.

Do you have any of these problems?

  • “I want to put the contents of this chapter into practice using my own manufacturing data.”
  • “I would like you to create customized Python training for our company.”
  • “I want to migrate Excel management to Python”
  • “I want to develop a data analysis platform for quality control and production management”

Services provided

ServiceOverview
Python training for the manufacturing industryPractical training using field data (online/face-to-face)
Data analysis infrastructure construction supportIntegrated management system design for production, quality, and cost data
KPI dashboard developmentReal-time manufacturing index visualization tool development
DX promotion consultingConsistent support from problem organization to implementation

📩 Contact: www.surikobo.co.jp/contact Please feel free to contact us first.