100 Exercises / Python / 100 Python Exercises for Data Analysis
Analyzing Production Quality with NumPy
Use NumPy to calculate and summarize 90 days of quality data. Learn array axes, broadcasting, filtering, variation, and process capability.
100 Exercises Chapter 7 (No.061-No.070): Introduction to NumPy
This is Chapter 7 (No.061–070) of 100 Python Exercises for Data Analysis. This chapter covers NumPy arrays and numerical calculations using fictional 90 days of quality data from three production lines.
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.
Example task
This is a problem faced by Mr. K, who is in charge of data analysis at a precision machinery parts factory.
Current situation
1. Daily production counts and defective numbers for 3 lines are accumulated in 90 days x 3 sheets.
2. Because a for loop is written to calculate the defect rate, the code is long and difficult to maintain.
3. Every time you answer the question, “When was the day last month when the defect rate was the highest?”
Searching for 270 numbers manually
4. Calculate statistics individually in Excel to evaluate stability (variation) for each line
Using NumPy, you can calculate the defect rate of 270 items (3 lines x 90 days) in 1 line, Find the maximum value, minimum value, average, and standard deviation using one function, You can instantly extract the warning date (defect rate > threshold) using fancy index.
Common situations in the field
| Scene | Task |
|---|---|
| Batch calculation of defect rate | for Process 90 rows sequentially in a loop. The code is long and slow as the number of lines increases |
| Average by month and line | Apply Excel’s AVERAGE function to each column and sheet individually |
| Extracting abnormal values (warning days) | Manually filtering “days with defect rate > 2%”, there is a risk of oversight |
| Stability evaluation | Calculate the standard deviation of each line individually and calculate the coefficient of variation (CV) by hand |
| Horizontal comparison of multiple lines | Files are separated for each line, making it difficult to grasp the overall picture |
NumPy’s Vector operations, Boolean index, Aggregation functions (axis specification)
When combined, these tasks can be automated with just a few lines of code.
Common mistakes
Although NumPy appears to have low learning costs, it has the following pitfalls when working with manufacturing data:
-
axisorientation confusion In a two-dimensional array,np.mean(data, axis=0)is the average in the column direction (daily),axis=1is the “row direction (by line)” average.
Checkshapefirst and understand which is the row and which is the column before operating it. -
Slice returns view The slice of
sub = array[10:20]is a reference, not a copy.
If you setsub[0] = 99, the originalarraywill also change.
Specify.copy()to prevent unintended changes -
dtype pitfalls
int32Division between arrays results in float, but Please be aware that truncation occurs in integer operations (//and%) -
Boolean index returns copy In-place assignment of
array[array > 2.0] = 0changes the original array, butsub = array[array > 2.0]returns a new copy.
Be careful because the behavior is different between assignment and reference.
Exercises in this chapter
| No. | Title | Usage in manufacturing industry |
|---|---|---|
| 061 | Understanding the role of NumPy | Comparing list and NumPy expressions and results |
| 062 | Import NumPy | Check import and frequently used functions |
| 063 | Create a NumPy array | Array the daily production count, defective number, and dimension measurements |
| 064 | Check the array shape | Understand the structure of two-dimensional data with shape / ndim / dtype / size |
| 065 | Extracting elements of an array | Extracting a specific date or line using index, slice, or 2-dimensional access |
| 066 | Batch calculation for arrays | Simultaneous calculation of defect rate, sales, and loss for 270 items (broadcast) |
| 067 | Calculate the average value | axis Batch calculation and bar graph visualization of average defect rate by line and month |
| 068 | Calculate maximum and minimum values | Identify worst and best days with argmax / argmin |
| 069 | Calculate standard deviation | Horizontal comparison of line quality stability using coefficient of variation (CV) |
| 070 | Extract data that meets the conditions | Automatically extract warning dates with np.where and visualize with scatter plot |
Preparing the Python 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.
import platform
import sys
print(f"OS: {platform.platform()}")
print(f"Python: {sys.version.split()[0]}")
OS: macOS-26.5.2-arm64-arm-64bit-Mach-O
Python: 3.14.4
Setup: Imports and display settings (expand)
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import datetime
matplotlib.rcParams['font.family'] = 'Hiragino Maru Gothic Pro'
%config InlineBackend.figure_format = 'svg'
np.random.seed(42)
print("Library loading completed")
print(f" NumPy : {np.__version__}")
print(f" Matplotlib: {matplotlib.__version__}")
Library loading completed
NumPy : 2.5.1
Matplotlib: 3.11.0
Creating the sample data
Assumed scenario: Precision mechanical parts factory / machining line quality control team
Period: January 1, 2024 - March 30, 2024 (90 days)
Management target: 3 product lines (precision shafts, bearings, flanges)
Data format: 2D NumPy array — shape: (3, 90) = (number of lines, number of days)
Setup: Generate the sample data (expand)
np.random.seed(42)
# ── Basic settings ────────────────────────────────────────────
lines = ["M1-Precision shaft", "M2-Bearing", "M3-flange"]
unit_prices = np.array([2400, 1800, 1200]) # yen/piece
n_days = 90 # 2024-01-01~03-30
base_date = datetime.date(2024, 1, 1)
# Month index (0=January: 31 days, 1=February: 29 days, 2=March: 30 days)
month_idx = np.array([0]*31 + [1]*29 + [2]*30, dtype=np.int32)
# ── Daily production count (3 lines x 90 days) ──────────────────────────
base_prod = [450, 380, 550]
prod_2d = np.array([
np.random.randint(b - 20, b + 21, size=n_days)
for b in base_prod
], dtype=np.int32) # shape: (3, 90)
# ── Daily defective number ──────────────────────────────────────────
dr_base = [0.018, 0.022, 0.014]
defect_2d = np.array([
np.maximum(1, np.round(
prod_2d[i] * dr_base[i] + np.random.randn(n_days) * 1.2
).astype(int))
for i in range(3)
], dtype=np.int32) # shape: (3, 90)
# ── Daily defect rate ──────────────────────────────────────────
defect_rates_2d = defect_2d / prod_2d * 100 # shape: (3, 90), dtype: float64
# ── Confirmation display ────────────────────────────────────────────
print(f"array size: prod_2d{prod_2d.shape}, defect_2d{defect_2d.shape}, "
f"defect_rates_2d{defect_rates_2d.shape}")
print()
print(f"{'line':<14} {'Period total (production)':>10} {'Period total (bad)':>10} {'Average defect rate':>10} {'Maximum defect rate':>10}")
print("=" * 58)
for i, line in enumerate(lines):
print(f"{line:<14} {int(prod_2d[i].sum()):>10,} {int(defect_2d[i].sum()):>10} "
f"{float(defect_rates_2d[i].mean()):>9.2f}% {float(defect_rates_2d[i].max()):>9.2f}%")
array size: prod_2d(3, 90), defect_2d(3, 90), defect_rates_2d(3, 90)
line Period total (production) Period total (bad) Average defect rate Maximum defect rate
==========================================================
M1-Precision shaft 40,387 745 1.84% 2.55%
M2-Bearing 34,339 771 2.24% 2.89%
M3-flange 49,581 711 1.43% 1.94%
No.061: Understand the role of NumPy
Use in practice
When calculating the daily defect rate of a production line, the Python for loop
90 loops are required. Using NumPy’s vector operations,
The same calculation is completed by applying to one row/entire array. Even if the data increases to 10,000 rows or 10 lines, the NumPy code will not change.
Approach
NumPy runs array calculations through compiled operations. It can be faster than Python loops for bulk numerical work, but the difference depends on the operation, array size, and environment. This example compares the code and results; it does not benchmark speed.
Check with Python
# Comparing the simplicity of Python lists (for loops) and NumPy
production_list = list(prod_2d[0]) # 90 days of M1
defect_list = list(defect_2d[0])
# ── Pure Python: Calculate defect rate with for loop ────────────────
defect_rates_py = []
for prod, def_count in zip(production_list, defect_list):
defect_rates_py.append(def_count / prod * 100)
mean_py = sum(defect_rates_py) / len(defect_rates_py)
# ── NumPy: 1 line in vector operation ──────────────────────────────
defect_rates_np = defect_2d[0] / prod_2d[0] * 100
mean_np = defect_rates_np.mean()
print("=== Comparison of calculation results (M1-Precision shaft, 90 days) ===")
print(f" Python top of list5records: {[round(r, 2) for r in defect_rates_py[:5]]}")
print(f" NumPy array top5records: {defect_rates_np[:5].round(2)}")
print()
print(f" Python average: {mean_py:.4f}%")
print(f" NumPy average : {mean_np:.4f}% (No error)")
print()
print("=== Code difference ===")
print("Python: for loop 4 lines + sum/len")
print("NumPy : defect_2d[0] / prod_2d[0] * 100 ← Completed in one line")
print()
print(f" Difference in type: Python={type(defect_rates_py).__name__}, NumPy={type(defect_rates_np).__name__}")
print(f" NumPy dtype: {defect_rates_np.dtype}")
=== Comparison of calculation results (M1-Precision shaft, 90 days) ===
Python top of list5records: [np.float64(1.71), np.float64(1.53), np.float64(2.03), np.float64(2.06), np.float64(2.0)]
NumPy array top5records: [1.71 1.53 2.03 2.06 2. ]
Python average: 1.8439%
NumPy average : 1.8439% (No error)
=== Code difference ===
Python: for loop 4 lines + sum/len
NumPy : defect_2d[0] / prod_2d[0] * 100 ← Completed in one line
Difference in type: Python=list, NumPy=ndarray
NumPy dtype: float64
Interpreting the results
The list and NumPy calculations agree. defect_2d[0] / prod_2d[0] * 100 calculates 90 daily rates in one array expression. The expression stays the same when the array contains more observations.
No.062: Import NumPy
Use in practice
import numpy as np is the standard NumPy import method. The np alias is an industry standard and is used by other libraries as well.
It is designed to expect NumPy arrays as input.
Approach
NumPy arrays can exchange data with libraries such as pandas and scikit-learn, although those libraries support other data types too. Understanding array shapes and types makes it easier to check the inputs passed to their functions.
Check with Python
import numpy as np
print(f"NumPy version: {np.__version__}")
print()
# NumPy functions commonly used in manufacturing data analysis
kpi_funcs = [
("np.array()", "List → array conversion"),
("np.zeros(n)", "Initializing zero arrays (alert flags, etc.)"),
("np.arange(n)", "Sequential number array (generate daily index)"),
("np.mean()", "Average value (monthly average of defect rate)"),
("np.std()", "Standard deviation (quality stability evaluation)"),
("np.max() / min()", "Maximum/Minimum (worst day/best day)"),
("np.argmax()", "Maximum value index (day)"),
("np.where()", "Extraction/labeling based on conditions"),
("np.sum(axis=)", "Total (accumulated by row/column by specifying axis)"),
("np.cumsum()", "Cumulative sum (monthly cumulative production count)"),
]
print(f"{'function':<28} {'Utilization in manufacturing data'}")
print("=" * 68)
for fname, desc in kpi_funcs:
print(f" {fname:<26} {desc}")
print()
# NumPy constants
print(f"np.pi = {np.pi:.6f} (Circumference and area calculation of circular parts)")
print(f"np.inf = {np.inf} (as an initial value with no upper limit)")
print(f"np.nan = {np.nan} (Representation of missing values)")
NumPy version: 2.5.1
function Utilization in manufacturing data
====================================================================
np.array() List → array conversion
np.zeros(n) Initializing zero arrays (alert flags, etc.)
np.arange(n) Sequential number array (generate daily index)
np.mean() Average value (monthly average of defect rate)
np.std() Standard deviation (quality stability evaluation)
np.max() / min() Maximum/Minimum (worst day/best day)
np.argmax() Maximum value index (day)
np.where() Extraction/labeling based on conditions
np.sum(axis=) Total (accumulated by row/column by specifying axis)
np.cumsum() Cumulative sum (monthly cumulative production count)
np.pi = 3.141593 (Circumference and area calculation of circular parts)
np.inf = inf (as an initial value with no upper limit)
np.nan = nan (Representation of missing values)
Interpreting the results
Functions such as np.mean, np.std, np.argmax, and np.where support common summaries and selections. np.inf can initialize a minimum-search variable. np.nan represents a missing floating-point value; np.mean propagates it, while np.nanmean excludes it. Check how many observations are excluded.
No.063: Create NumPy array
Use in practice
Learn how to create manufacturing data as a NumPy array. Data read from CSV or Excel is ultimately converted to a NumPy array for processing. If you use np.random.normal(), you can also use simulation data of dimension measurements.
It can be generated in a form close to reality.
Approach
Create arrays by converting lists, setting initial values, generating evenly spaced values, or sampling random values. The dimension example assumes a normal distribution with mean and variance . The second argument of np.random.normal(mean, std, size) is the standard deviation, not the variance. Check separately whether actual measurements resemble a normal distribution.
Check with Python
# 4 ways to create NumPy arrays
# 1. Convert from list with np.array()
weekly_prod_063 = np.array([450, 462, 438, 471, 445, 457, 448])
print(f"1. np.array() : {weekly_prod_063} shape={weekly_prod_063.shape}")
# 2. Initialize with np.zeros() (alert flags, etc.)
alert_flags = np.zeros(n_days, dtype=np.int8)
print(f"2. np.zeros() : {alert_flags[:5]} ... shape={alert_flags.shape}, dtype={alert_flags.dtype}")
# 3. Sequential numbers with np.arange()
day_indices = np.arange(n_days) # 0~89
print(f"3. np.arange(): {day_indices[:7]} ... shape={day_indices.shape}")
# 4. Generate dimension measurements with np.random.normal() (shaft diameter inspection of precision shaft)
target_diam = 25.000 # Target diameter mm
tolerance = 0.050 # Tolerance ±0.05mm
sigma_diam = tolerance / 3 # 3σ = half the tolerance width → σ = 0.0167mm
measurements = np.random.normal(target_diam, sigma_diam, size=30)
print()
print("=== M1-Precision shaft diameter measurement (n=30 samples) ===")
print(f" Target value : {target_diam:.3f} mm Tolerance: ±{tolerance:.3f} mm")
print(f" top5records : {measurements[:5].round(4)} mm")
print(f" average : {measurements.mean():.4f} mm")
print(f" range : {measurements.min():.4f} ~ {measurements.max():.4f} mm")
print()
# Specifying dtype
arr_int = np.array([1.7, 2.3, 3.9], dtype=np.int32) # round down decimal
arr_float = np.array([1, 2, 3], dtype=np.float64)
print(f"dtype=int32 conversion: {arr_int} (decimals are rounded down)")
print(f"dtype=float64conversion: {arr_float}")
1. np.array() : [450 462 438 471 445 457 448] shape=(7,)
2. np.zeros() : [0 0 0 0 0] ... shape=(90,), dtype=int8
3. np.arange(): [0 1 2 3 4 5 6] ... shape=(90,)
=== M1-Precision shaft diameter measurement (n=30 samples) ===
Target value : 25.000 mm Tolerance: ±0.050 mm
top5records : [25.0187 24.976 24.998 24.9987 24.9816] mm
average : 24.9983 mm
range : 24.9620 ~ 25.0396 mm
dtype=int32 conversion: [1 2 3] (decimals are rounded down)
dtype=float64conversion: [1. 2. 3.]
Interpreting the results
For a target diameter of 25.000 mm and a tolerance of mm, the standard deviation is set to mm. Thus the half-width is and the full 0.100 mm width is . A normal distribution centered between the specification limits puts about 99.73% of values inside them. This does not guarantee that a sample of 30 will show that proportion.
Converting floating-point values to int32 truncates toward zero. Also check that values fit within the integer type’s range.
No.064: Check the shape of the array
Use in practice
When handling manufacturing data as a two-dimensional array (matrix),
Whether the rows are lines and the columns are dates or the rows are dates and columns are lines.
It is important to check shape before operating. If the direction of the axis is incorrect, the results of averaging and aggregation will be completely reversed.
Approach
shape gives the length of each axis, ndim the number of dimensions, dtype the element type, and size the number of elements. Shape alone does not tell you what each axis means; document that axis 0 represents lines and axis 1 represents days.
Check with Python
# Understand the structure of an array using shape / ndim / dtype / size
print("=== 1-dimensional array (M1 daily production quantity) ===")
a1 = prod_2d[0] # shape: (90,)
print(f" shape: {a1.shape} → {a1.shape[0]} days")
print(f" ndim : {a1.ndim} → 1dimension")
print(f" dtype: {a1.dtype} → integer type")
print(f" size : {a1.size} → Number of elements")
print()
print("=== 2D array (all lines x all days) ===")
print(f" shape: {prod_2d.shape}")
print(f" → rows = {prod_2d.shape[0]}Line (M1, M2, M3)")
print(f" → columns = {prod_2d.shape[1]}day (2024-01-01~03-30)")
print(f" ndim : {prod_2d.ndim} → 2dimension")
print(f" dtype: {prod_2d.dtype}")
print(f" size : {prod_2d.size} → Total number of elements ({prod_2d.shape[0]} × {prod_2d.shape[1]})")
print()
print("=== Defect rate array (float64) ===")
print(f" shape: {defect_rates_2d.shape}, dtype: {defect_rates_2d.dtype}")
print()
# Check axis using shape
print("=== Difference between axis=0 vs axis=1 (check with np.sum) ===")
sum_axis0 = prod_2d.sum(axis=0) # Total of all lines for each day → shape: (90,)
sum_axis1 = prod_2d.sum(axis=1) # All-day total for each line → shape: (3,)
print(f" axis=0(column direction, total by day): shape={sum_axis0.shape} top3days={sum_axis0[:3]}")
print(f" axis=1(Row direction, line total): shape={sum_axis1.shape} value={sum_axis1}")
print()
for i, line in enumerate(lines):
print(f" {line} 90Total daily production: {int(sum_axis1[i]):,} units")
=== 1-dimensional array (M1 daily production quantity) ===
shape: (90,) → 90 days
ndim : 1 → 1dimension
dtype: int32 → integer type
size : 90 → Number of elements
=== 2D array (all lines x all days) ===
shape: (3, 90)
→ rows = 3Line (M1, M2, M3)
→ columns = 90day (2024-01-01~03-30)
ndim : 2 → 2dimension
dtype: int32
size : 270 → Total number of elements (3 × 90)
=== Defect rate array (float64) ===
shape: (3, 90), dtype: float64
=== Difference between axis=0 vs axis=1 (check with np.sum) ===
axis=0(column direction, total by day): shape=(90,) top3days=[1414 1416 1369]
axis=1(Row direction, line total): shape=(3,) value=[40387 34339 49581]
M1-Precision shaft 90Total daily production: 40,387 units
M2-Bearing 90Total daily production: 34,339 units
M3-flange 90Total daily production: 49,581 units
Interpreting the results
This array has shape (3, 90), with lines on axis 0 and days on axis 1. Aggregating with axis=0 removes the line axis and returns 90 daily results. Using axis=1 removes the day axis and returns three line results. For example, np.mean(prod_2d, axis=1) gives average daily production for each line.
No.065: Extract elements of array
Use in practice
“Extract only the data for the second week of the M2 line” “Compare the data for January 1st for all lines” Such access to specific dates and specific lines is routinely required for manufacturing data analysis. NumPy’s indexing and slicing allows us to write this concisely.
Approach
NumPy’s slice returns a view. If you need a copy, use .copy().
Fancy indexing (indexing by integer array/Boolean array) returns a copy. Being aware of which one you are using when processing data is the key to preventing bugs.
Check with Python
# Extract elements using index, slice, and 2D access
prod_m1 = prod_2d[0] # M1 line, shape: (90,)
print("=== 1D index access ===")
print(f" first day [0] : {prod_m1[0]:,} units")
print(f" last days [-1] : {prod_m1[-1]:,} units")
print(f" 10day [9] : {prod_m1[9]:,} units")
print()
print("=== Slice by week ===")
week1 = prod_m1[:7] # Week 1 (1/1-1/7)
week2 = prod_m1[7:14] # Week 2 (1/8-1/14)
print(f" No.1week ( 1/ 1~ 1/ 7): {week1} Total={int(week1.sum()):,}units")
print(f" No.2week ( 1/ 8~ 1/14): {week2} Total={int(week2.sum()):,}units")
print()
print("=== 2D array access ===")
print(f" M1 of1day prod_2d[0, 0] = {prod_2d[0, 0]:,} units")
print(f" M2 of1day prod_2d[1, 0] = {prod_2d[1, 0]:,} units")
print(f" of all lines1day prod_2d[:, 0] = {prod_2d[:, 0]} (Number of production for each line)")
print(f" M3 all of90days prod_2d[2, :].shape = {prod_2d[2, :].shape}")
print()
print("=== Copy the slice with view → .copy() ===")
sub = prod_m1[10:15].copy() # get a copy
original_val = prod_m1[10]
sub[0] = 9999
print(f" sub[0] The 9999 changed to → original array prod_m1[10] = {prod_m1[10]} (No change)")
=== 1D index access ===
first day [0] : 468 units
last days [-1] : 464 units
10day [9] : 440 units
=== Slice by week ===
No.1week ( 1/ 1~ 1/ 7): [468 458 444 437 450 468 448] Total=3,173units
No.2week ( 1/ 8~ 1/14): [452 440 440 453 465 469 453] Total=3,172units
=== 2D array access ===
M1 of1day prod_2d[0, 0] = 468 units
M2 of1day prod_2d[1, 0] = 394 units
of all lines1day prod_2d[:, 0] = [468 394 552] (Number of production for each line)
M3 all of90days prod_2d[2, :].shape = (90,)
=== Copy the slice with view → .copy() ===
sub[0] The 9999 changed to → original array prod_m1[10] = 453 (No change)
Interpreting the results
prod_2d[:, 0] selects the first day for all three lines. Calling .copy() creates an independent array: changing sub[0] to 9999 leaves prod_m1[10] unchanged.
No.066: Batch calculation for arrays
Use in practice
NumPy’s broadcast feature allows arrays of different shapes to
You can automatically match the shapes and perform calculations. If you transform unit_prices (form (3,)) to (3, 1),
Multiply by the production count array of (3, 90),
Sales for all lines and all days can be calculated at once without loops.
Approach
Broadcasting compares dimensions from the trailing axis. Dimensions are compatible when they are equal or one of them is 1; missing leading dimensions are treated as size 1. For example, elementwise multiplication of shapes (3, 1) and (3, 90) produces (3, 90). This is not matrix multiplication.
Check with Python
# Calculate 270 KPIs at once using vector operations and broadcasting
# Number of good products (vector subtraction)
good_units_2d = prod_2d - defect_2d # shape: (3, 90)
# Sales (broadcast: transformed to unit_prices (3,) → (3,1))
revenue_2d = good_units_2d * unit_prices.reshape(3, 1) # shape: (3, 90)
# Loss (number of defects × unit price × (1 + disposal cost rate))
penalty = 0.30
loss_2d = defect_2d * unit_prices.reshape(3, 1) * (1 + penalty) # shape: (3, 90)
print("=== Vector operation result (first 3 days of each line) ===")
print(f"{'line':<14} {'days':>4} {'production':>6} {'defective':>5} {'Defect rate (%)':>10} {'Good product sales':>12} {'defect loss':>10}")
print("-" * 66)
for i, line in enumerate(lines):
for j in range(3):
dr = float(defect_rates_2d[i, j])
print(f"{line if j==0 else '':<14} {j+1:>4} {int(prod_2d[i,j]):>6,} "
f"{int(defect_2d[i,j]):>5} {dr:>9.2f}% "
f"{int(revenue_2d[i,j]):>12,} {int(loss_2d[i,j]):>10,}")
print()
print("=== Weekly aggregation (slice + sum) ===")
for i, line in enumerate(lines):
w1_prod = int(prod_2d[i, :7].sum())
w1_revenue = int(revenue_2d[i, :7].sum())
w1_loss = int(loss_2d[i, :7].sum())
print(f" {line}: No.1weekly production {w1_prod:,}units / sales {w1_revenue:,}JPY / loss {w1_loss:,}JPY")
print()
print("=== Total period/all lines ===")
print(f" Total production count : {int(prod_2d.sum()):,} units")
print(f" total sales : {int(revenue_2d.sum()):,} JPY")
print(f" total loss : {int(loss_2d.sum()):,} JPY")
=== Vector operation result (first 3 days of each line) ===
line days production defective Defect rate (%) Good product sales defect loss
------------------------------------------------------------------
M1-Precision shaft 1 468 8 1.71% 1,104,000 24,960
2 458 7 1.53% 1,082,400 21,840
3 444 9 2.03% 1,044,000 28,080
M2-Bearing 1 394 7 1.78% 696,600 16,380
2 392 11 2.81% 685,800 25,740
3 364 7 1.92% 642,600 16,380
M3-flange 1 552 7 1.27% 654,000 10,920
2 566 8 1.41% 669,600 12,480
3 561 9 1.60% 662,400 14,040
=== Weekly aggregation (slice + sum) ===
M1-Precision shaft: No.1weekly production 3,173units / sales 7,473,600JPY / loss 184,080JPY
M2-Bearing: No.1weekly production 2,701units / sales 4,753,800JPY / loss 140,400JPY
M3-flange: No.1weekly production 3,850units / sales 4,554,000JPY / loss 85,800JPY
=== Total period/all lines ===
Total production count : 124,307 units
total sales : 214,207,200 JPY
total loss : 5,237,700 JPY
Interpreting the results
Reshaping the three unit prices to (3, 1) lets broadcasting apply each price across its line’s 90 days. prod_2d.sum() totals the whole array, sum(axis=1) gives one total per line, and sum(axis=0) gives one per day.
No.067: Calculate the average value
Use in practice
Use the axis argument of np.mean() to calculate line or daily averages. For monthly summaries, select days with a Boolean mask based on month_idx. The monthly example uses list comprehensions to iterate over line and month combinations.
Approach
axis=0 is “Crush rows and aggregate in columns” → Daily aggregate (90 results)
axis=1 is “collapse columns and aggregate in row direction” → aggregate by line (3 results)
If you need a weighted average, use np.average(data, weights=weights).
Check with Python
# Aggregation with axis specified using np.mean()
# Average defect rate by line (average for each line)
line_mean_dr = np.mean(defect_rates_2d, axis=1) # shape: (3,)
# Daily average defect rate for all lines (average of each column)
day_mean_dr = np.mean(defect_rates_2d, axis=0) # shape: (90,)
print("=== Average defect rate by line (axis=1) ===")
for i, line in enumerate(lines):
print(f" {line}: {line_mean_dr[i]:.3f}%")
print()
# Monthly average (Boolean mask aggregation using month_idx)
month_names_j = ["January", "February", "March"]
print(f"=== Average defect rate by line/month ===")
print(f"{'line':<14} {'January':>8} {'February':>8} {'March':>8}")
print("-" * 42)
monthly_avg_067 = np.array([
[np.mean(defect_rates_2d[i][month_idx == m]) for m in range(3)]
for i in range(3)
])
for i, line in enumerate(lines):
row = " ".join(f"{monthly_avg_067[i, m]:.2f}%" for m in range(3))
print(f" {line:<14} {row}")
print()
print(f" Daily average (first5day): {day_mean_dr[:5].round(3)}")
=== Average defect rate by line (axis=1) ===
M1-Precision shaft: 1.844%
M2-Bearing: 2.244%
M3-flange: 1.434%
=== Average defect rate by line/month ===
line January February March
------------------------------------------
M1-Precision shaft 1.83% 1.86% 1.84%
M2-Bearing 2.23% 2.26% 2.24%
M3-flange 1.43% 1.41% 1.46%
Daily average (first5day): [1.585 1.916 1.851 1.807 1.92 ]
# Comparison bar graph of monthly average defect rate
fig, ax = plt.subplots(figsize=(10, 5))
x = np.arange(3)
width = 0.28
colors_067 = ["#4C72B0", "#DD8452", "#55A868"]
for i, line in enumerate(lines):
ax.bar(x + (i - 1) * width, monthly_avg_067[i], width,
label=line, color=colors_067[i], alpha=0.88)
ax.axhline(2.0, color="red", linewidth=1.5, linestyle="--", alpha=0.7,
label="Warning line (2.0%)")
ax.set_title("Monthly average defect rate by product line (np.mean + axis aggregation)",
fontsize=13, pad=10)
ax.set_xlabel("Month", fontsize=11)
ax.set_ylabel("Average defect rate (%)", fontsize=11)
ax.set_xticks(x)
ax.set_xticklabels(month_names_j)
ax.legend(fontsize=10)
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
Interpreting the results
M2-bearing’s monthly mean defect rates are 2.23%, 2.26%, and 2.24%, all above the 2.0% threshold. The monthly means for M1 and M3 are below 2.0%. March includes only the 30 days through March 30.
These are arithmetic means of daily rates. For the period’s overall defect rate, divide total defective units by total production or use a production-weighted mean.
No.068: Calculate maximum and minimum values
Use in practice
“When was the day when the defect rate was the highest?” “Which line was the day when the number of production was the lowest?”
To answer this question, you need both the maximum and minimum values and their index (what day). np.argmax() / np.argmin() allows you to identify values and dates at the same time.
Approach
np.max() returns the maximum value, but “which position” is obtained using np.argmax(). To convert from daily index (0-based) to actual date:
Use base_date + datetime.timedelta(days=idx). It can be used to automate the process of regularly identifying and reporting the “worst day” within a month.
Check with Python
import datetime
# Maximum/minimum defect rate for the entire period
overall_max = float(np.max(defect_rates_2d))
overall_min = float(np.min(defect_rates_2d))
print(f"=== Extreme value of defect rate for all lines and all periods ===")
print(f" Maximum defect rate : {overall_max:.2f}%")
print(f" Minimum defect rate : {overall_min:.2f}%")
print()
# Identify the worst and best days for each line
print(f"{'line':<14} {'Maximum defect rate':>10} {'worst day':>10} {'Minimum defect rate':>10} {'best day':>10}")
print("=" * 56)
for i, line in enumerate(lines):
max_dr = float(defect_rates_2d[i].max())
min_dr = float(defect_rates_2d[i].min())
max_day = int(np.argmax(defect_rates_2d[i]))
min_day = int(np.argmin(defect_rates_2d[i]))
max_date = (base_date + datetime.timedelta(days=max_day)).strftime("%m/%d")
min_date = (base_date + datetime.timedelta(days=min_day)).strftime("%m/%d")
print(f" {line:<14} {max_dr:>9.2f}% {max_date:>10} {min_dr:>9.2f}% {min_date:>10}")
print()
# Day with the highest production total for all lines
daily_total_prod = prod_2d.sum(axis=0) # shape: (90,)
best_day_idx = int(np.argmax(daily_total_prod))
worst_day_idx = int(np.argmin(daily_total_prod))
best_date = (base_date + datetime.timedelta(days=best_day_idx)).strftime("%m/%d")
worst_date = (base_date + datetime.timedelta(days=worst_day_idx)).strftime("%m/%d")
print(f"=== Total of all lines Extreme value of production count ===")
print(f" maximum production date: {best_date} ({int(daily_total_prod[best_day_idx]):,} units)")
print(f" Minimum production date: {worst_date} ({int(daily_total_prod[worst_day_idx]):,} units)")
=== Extreme value of defect rate for all lines and all periods ===
Maximum defect rate : 2.89%
Minimum defect rate : 0.90%
line Maximum defect rate worst day Minimum defect rate best day
========================================================
M1-Precision shaft 2.55% 01/15 1.32% 03/20
M2-Bearing 2.89% 01/18 1.53% 01/11
M3-flange 1.94% 01/15 0.90% 03/20
=== Total of all lines Extreme value of production count ===
maximum production date: 03/02 (1,433 units)
Minimum production date: 03/24 (1,322 units)
Interpreting the results
np.argmax(defect_rates_2d[i]) gives the position of each line’s maximum rate. Adding that number of days to base_date gives its date. For real data, compare high-rate dates with records of materials, equipment, and staffing to investigate possible causes.
No.069: Calculate standard deviation
Use in practice
Even if the average defect rate is the same, lines with large dispersion (standard deviation) are The quality is not stable from day to day, making it difficult to manage. Using the coefficient of variation (CV = standard deviation / mean), You can horizontally compare the stability of lines with different units and levels.
Approach
np.std(data) returns the population standard deviation (denominator = n). For sample estimation, use np.std(data, ddof=1) (sample standard deviation, denominator = n-1). At manufacturing sites, population standard deviation is often used as “all production days of this month = population”. Standard deviation is the basic metric when calculating Process Capability Index (Cp/Cpk), such as dimension measurements.
Check with Python
# CV bands and the 1.33 threshold are illustrative; assess process stability separately.
# Evaluate quality stability with np.std(), np.var()
print(f"{'line':<14} {'Average defect rate':>10} {'standard deviation':>10} {'Coefficient of variation CV':>12} {'Stability evaluation':>12}")
print("=" * 62)
for i, line in enumerate(lines):
mean_v = float(np.mean(defect_rates_2d[i]))
std_v = float(np.std(defect_rates_2d[i])) # population standard deviation
cv_pct = std_v / mean_v * 100
stability = "◎ Stable" if cv_pct < 10 else ("○ Normal" if cv_pct < 20 else "△ Unstable")
print(f" {line:<14} {mean_v:>9.2f}% {std_v:>9.3f}% {cv_pct:>10.1f}% {stability:>12}")
print()
# Dimensional inspection: Calculation of process capability index (Cp)
print("=== M1-Precision shaft diameter process capability evaluation ===")
mu_m = float(np.mean(measurements))
sigma_m = float(np.std(measurements)) # population standard deviation
usl = target_diam + tolerance # Upper limit specification value
lsl = target_diam - tolerance # Lower limit specification value
cp = (usl - lsl) / (6 * sigma_m) # Process capability index Cp
cpk = min(usl - mu_m, mu_m - lsl) / (3 * sigma_m) # Cpk (bias consideration)
print(f" Target value: {target_diam:.3f} mm Tolerance: ±{tolerance:.3f} mm")
print(f" Measurement average: {mu_m:.4f} mm standard deviation: {sigma_m:.4f} mm")
print(f" Cp = {cp:.2f} (1.33 Pass with above: {'✅ Passed' if cp >= 1.33 else '❌ Needs improvement'})")
print(f" Cpk = {cpk:.2f} (1.33 Pass with above: {'✅ Passed' if cpk >= 1.33 else '❌ Needs improvement'})")
print()
n_ng = int(np.sum((measurements < lsl) | (measurements > usl)))
print(f" Out of tolerance product: {n_ng} units / {len(measurements)} units")
line Average defect rate standard deviation Coefficient of variation CV Stability evaluation
==============================================================
M1-Precision shaft 1.84% 0.268% 14.6% ○ Normal
M2-Bearing 2.24% 0.319% 14.2% ○ Normal
M3-flange 1.43% 0.217% 15.1% ○ Normal
=== M1-Precision shaft diameter process capability evaluation ===
Target value: 25.000 mm Tolerance: ±0.050 mm
Measurement average: 24.9983 mm standard deviation: 0.0165 mm
Cp = 1.01 (1.33 Pass with above: ❌ Needs improvement)
Cpk = 0.98 (1.33 Pass with above: ❌ Needs improvement)
Out of tolerance product: 0 units / 30 units
Interpreting the results
The three CVs are about 14–15%, so all receive the exercise’s “normal” label. This is an illustrative rule, not evidence that the processes are statistically stable.
With upper and lower specification limits and , the capability indices are calculated as:
The example gives and . Under a stable, normal process centered between the specification limits, corresponds to about 66 parts per million outside the limits. Different centering or distribution shapes invalidate that rate. indicates an offset from the midpoint, but does not establish that variation is sufficiently small.
No.070: Extract data that meets the conditions
Use in practice
The process of “automatically extracting and reporting the days when the defect rate exceeds the warning line (2.0%)” is as follows:
It is one of the most frequently required operations in manufacturing data pipelines. Using NumPy’s Boolean index and np.where(),
Conditional filtering can be performed quickly using vector operations.
Approach
array[array > threshold] is filtering by boolean index,
Returns only the elements that meet the condition as a new array (copy). np.where(condition, true value, false value) selects two values depending on conditions
Array version of the ternary operator. It can be used to automatically add warning labels to management graphs.
Check with Python
# Extracting warning date with boolean index and np.where()
threshold = 2.0 # Warning line (defect rate 2.0%)
print("=== Warning date extraction by Boolean index ===")
for i, line in enumerate(lines):
alert_mask = defect_rates_2d[i] > threshold # boolean array, shape: (90,)
alert_count = int(alert_mask.sum())
if alert_count > 0:
alert_dr = defect_rates_2d[i][alert_mask] # fancy index
print(f" {line}: warning day {alert_count:2d}days / {n_days}days "
f"maximum {float(alert_dr.max()):.2f}% Warning day average {float(alert_dr.mean()):.2f}%")
else:
print(f" {line}: warning day 0days / {n_days}days (normal all day)")
print()
# Add a label with np.where() (M1 first 10 days)
labels_m1 = np.where(defect_rates_2d[0] > threshold, "🔴 Warning", "✅ Normal")
print("=== Status label by np.where() (M1, first 10 days) ===")
for j in range(10):
d = (base_date + datetime.timedelta(days=j)).strftime("%m/%d")
print(f" {d}: {defect_rates_2d[0, j]:.2f}% {labels_m1[j]}")
print()
# Day when multiple lines issued a warning at the same time
simultaneous = int(np.sum(np.sum(defect_rates_2d > threshold, axis=0) >= 2))
print(f"2Number of days where above the line was warned on the same day: {simultaneous} days")
=== Warning date extraction by Boolean index ===
M1-Precision shaft: warning day 26days / 90days maximum 2.55% Warning day average 2.17%
M2-Bearing: warning day 71days / 90days maximum 2.89% Warning day average 2.36%
M3-flange: warning day 0days / 90days (normal all day)
=== Status label by np.where() (M1, first 10 days) ===
01/01: 1.71% ✅ Normal
01/02: 1.53% ✅ Normal
01/03: 2.03% 🔴 Warning
01/04: 2.06% 🔴 Warning
01/05: 2.00% ✅ Normal
01/06: 2.14% 🔴 Warning
01/07: 1.56% ✅ Normal
01/08: 1.77% ✅ Normal
01/09: 1.36% ✅ Normal
01/10: 1.59% ✅ Normal
2Number of days where above the line was warned on the same day: 21 days
# Daily defect rate trends for all lines + warning day highlights (3 panels)
fig, axes = plt.subplots(3, 1, figsize=(12, 8), sharex=True)
colors_070 = ["#4C72B0", "#DD8452", "#55A868"]
day_range = np.arange(n_days)
for i, (ax, line) in enumerate(zip(axes, lines)):
dr = defect_rates_2d[i]
alert_mask = dr > threshold
ax.plot(day_range, dr, color=colors_070[i], linewidth=1.5, alpha=0.7)
ax.scatter(day_range[alert_mask], dr[alert_mask],
color="red", zorder=5, s=45, label=f"Warning date ({int(alert_mask.sum())}day)")
ax.axhline(threshold, color="red", linestyle="--", linewidth=1.0, alpha=0.6)
ax.set_title(f"{line} ─ warning day: {int(alert_mask.sum())} days / {n_days} days", fontsize=11)
ax.set_ylabel("Defect rate (%)", fontsize=10)
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
axes[-1].set_xlabel("Daily index (0 = 2024-01-01)", fontsize=11)
plt.suptitle("Daily defect rate trends and warning date extraction by product line (np.where / Boolean index)",
fontsize=13, y=1.01)
plt.tight_layout()
plt.show()
Interpreting the results
Red points mark days above 2.0%. The Boolean mask selects those rates for calculating their maximum and mean. A visible cluster is a reason to inspect the underlying records, not evidence by itself of a particular cause.
Applying the exercises at work
The basics of NumPy learned in No.061-070 are the foundation for speeding up and improving accuracy of manufacturing data analysis.
1. Vector operations = “Code simplicity” and “Scalability”
for Not only does the defect rate calculation written in the loop become one line,
Even if the number of lines increases from 3 to 30, the (30, 90) array operates with the same code as (3, 90). You can write code that is strong enough to scale up manufacturing data.
2. Specifying axis = “Control of aggregation granularity”
By using axis=0 (daily aggregation) and axis=1 (line by line aggregation),
You can control “which dimension to leave” by yourself. Multidimensional aggregation such as “by month, by line, by shift”
This is achieved by combining NumPy’s axis and pandas’ groupby.
3. Boolean index = “dynamic filter”
By making warning lines, control limits, and tolerance thresholds variables,
One line of defect_rates_2d[defect_rates_2d > threshold]
You can immediately respond to “re-aggregation due to threshold change”. Parameterizing thresholds is a highly maintainable quality control system design.
4. Automatic calculation of process capability index (Cp / Cpk)
The process to automatically calculate Cp / Cpk from np.std and tolerance design values is as follows:
Directly linked to automatic generation of periodic quality reports. In Chapter 9 (Data processing using Polars), data from multiple processes is
Build a system for batch processing.
Applying the code to your data
These are the steps to implement NumPy, which you learned in this chapter, into a manufacturing data analysis system.
Step 1: NumPy array conversion of CSV data (about half a day)
For numeric CSV data, use np.loadtxt() or np.genfromtxt(). For a CSV with missing values, set delimiter and header options as needed, for example np.genfromtxt(file, delimiter=",", skip_header=1, filling_values=np.nan). These functions do not read Excel workbook files directly.
Step 2: Designing a 2D array (about 1 day)
First decide which axis is the line and which axis is the date,
Manage all data in the unified format of (n_lines, n_days). By unifying the shaft design, mistakes in axis specification can be prevented.
Step 3: Creating a file of threshold parameters (about half a day)
Design the system to read threshold values such as warning lines, control limits, and tolerances from CSV or JSON files. You can now recalculate just by changing the threshold without modifying the code.
Step 4: Automatic reporting of process capability index (about 1 day)
Apply Cp / Cpk calculation in this chapter No.069 to all lines, Build a script to automatically generate monthly quality reports. In Chapter 10 (Aggregation, Visualization, and Mini-Analysis), we will develop this into a more full-fledged report.
Summary
We will summarize what we learned in this chapter (No.061-070).
| No. | Skills | Utilization at manufacturing sites |
|---|---|---|
| 061 | Understanding the role of NumPy | Comparing results and readability with Python lists, and experiencing vector operations |
| 062 | Import NumPy | List of main functions and understand their uses in manufacturing data analysis |
| 063 | Create a NumPy array | Array the production count, defective number, and dimension measurements |
| 064 | Check the array shape | Understand the two-dimensional structure with shape/ndim/dtype/size |
| 065 | Retrieving elements from an array | Understanding indexes, slices, and view vs copy |
| 066 | Batch calculation for array | Calculate 270 KPIs in one line using broadcast |
| 067 | Calculate the average | axis Batch calculation of line and monthly averages and bar graph visualization |
| 068 | Calculating maximum and minimum values | Identifying the worst and best days using argmax/argmin |
| 069 | Calculate standard deviation | Evaluate stability using coefficient of variation and calculate process capability index using Cp/Cpk |
| 070 | Extract data that meets conditions | Automatically extract warning dates with Boolean index and visualize with scatter plot |
Chapter 8 (No.071-080) uses Polars, Treat the NumPy array in this chapter as a DataFrame, Learn aggregation, filtering, and CSV loading using column names.
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 use my company’s actual data to calculate the defect rate and process capacity in this chapter.”
- “I want to automate my quality control system with NumPy”
- “I want to create an automatic calculation tool for control charts (Xbar-R control charts) and process capability index”
- “I would like you to customize your in-house Python training and implement it for the manufacturing industry.”
Services provided
| Service | Overview |
|---|---|
| Python training for the manufacturing industry | Practical training using field data (online/face-to-face) |
| Quality control automation system | Automatic calculation and reporting of defect rate, Cp/Cpk, and control chart |
| Sensor data analysis platform | Anomaly detection and predictive maintenance system construction for time-series data |
| DX promotion consulting | Consistent support from problem resolution to implementation and establishment support |
📩 Contact: www.surikobo.co.jp/contact Please feel free to contact us first.