All articles →

100 Exercises / Python / 100 Python Exercises for Data Analysis

Cleaning Quality Inspection Data with Polars

Clean inspection data with Polars: select columns, filter rows, add KPIs, retain unknown defect counts, sort results, and remove duplicates.

100 Exercises Chapter 9 (No.081-No.090): Data processing by Polars

This is Chapter 9 (No.081–090) of 100 Python Exercises for Data Analysis. This chapter covers filtering, column operations, missing values, sorting, and deduplication using fictional EV-parts inspection data.

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 quality control teams at EV parts manufacturers.

Current situation
  1. Daily quality inspection data was received in CSV from 5 factories nationwide, and when combined, there were 315 items.
  2. If you look closely, there are 15 duplicates of the same record (data synchronization bug on the factory side)
  3. There are 30 rows where the number of defects is not recorded due to sensor failure.
  4. inspector_id is blank on days when the inspector did not log in to the system (45 cases)
  5. The factory_name column has a one-to-one correspondence with factory_id and is redundant—one is unnecessary.
  6. The raw_note column is a test memo and is not used in production analysis.

By combining Polars’ 10 data processing operations, you can eliminate these raw data quality issues. It is systematically organized, cleansed, and prepared for analysis.

Common situations in the field

SceneTask
Handling multi-column dataThere are many unnecessary columns in the collected data, making checking and processing complicated
Condition filteringManually extracting conditions such as “Defect rate > 2%” and “Specific factories only” each time using Excel
Adding KPI columnsThe number of good products, sales, and losses are manually calculated using Excel formulas
Column names in EnglishSystem output is English column names, which are manually changed each time for reporting
Checking for missing valuesNot sure how many values are missing in which columns
Aggregation errors due to missing valuesAggregating columns that contain NULL results in strange results
Duplicate dataDue to a data synchronization bug, the same record is not noticed twice
Sorting/RankingWe manually sort and check the worst defect rate rankings every time.

By mastering Polars’ 10 data processing operations, you can pipeline them.

Common mistakes

Although Polars’ data manipulation seems intuitive, there are some caveats in the context of manufacturing data:

  1. How to use select vs drop The basic policy is “select if there are few columns you want to keep” and “drop if there are few columns you want to delete”.
    For practical data with a large number of columns, drop is often more maintainable.

  2. Logical operation of filter Polars uses & (AND) and | (OR). Python’s and / or cannot be used.
    Multiple conditions must always be enclosed in parentheses () Example: df.filter((pl.col("a") > 2) & (pl.col("b") == "X"))

  3. Simultaneous evaluation of with_columns Multiple expressions in with_columns are evaluated simultaneously relative to the original DataFrame.
    If you want to use the calculation result of column A in the formula of column B, call with_columns twice. Use chain (.with_columns(...).with_columns(...))

  4. The order of missing value handling is important Decide what to use to fill in missing values as a business rule before operating.
    ”Fill with 0”, “Fill with previous and following values”, and “Delete” Please clarify in the comments as it is directly related to the prerequisites for analysis.

  5. unique’s keep Strategy When deduplicating, the records to be kept differ for keep="first" and keep="last".
    When sorted by timestamp, keep="first" is “older record first”

Exercises in this chapter

No.TitleMain Polars operations
081Select specific columnsdf.select(["col1", "col2", ...])
082Extract rows that meet the conditionsdf.filter(pl.col("col") > value)
083Add columndf.with_columns([expr.alias("name"), ...])
084Change column namedf.rename({"old_name": "new_name"})
085Delete unnecessary columnsdf.drop(["col1", "col2"])
086Check missing valuesdf.null_count()
087Remove missing valuesdf.drop_nulls(subset=["col"])
088Impute missing valuesdf.with_columns(pl.col("col").fill_null(value))
089Sort datadf.sort("col", descending=True)
090Delete duplicate datadf.unique(subset=["col1", ...], keep="first")

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.

[IN: 1]
import platform
import sys

print(f"OS: {platform.platform()}")
print(f"Python: {sys.version.split()[0]}")
[OUT: 1]
OS: macOS-26.5.2-arm64-arm-64bit-Mach-O
Python: 3.14.4
Setup: Imports and display settings (expand)
[IN: 2]
import numpy as np
import polars as pl
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"  Polars    : {pl.__version__}")
print(f"  Matplotlib: {matplotlib.__version__}")
[OUT: 2]
Library loading completed
  NumPy     : 2.5.1
  Polars    : 1.42.1
  Matplotlib: 3.11.0

Creating the sample data

Assumed scenario: Electronic component manufacturer for EV (electric vehicle) / Quality control team Period: January 4–23, 2024 (20 calendar days, including weekends) Management target: 5 factories x 3 production lines = 15 records / day Number of cases: 300 cases (20 days x 15) + 15 duplicates = 315 cases

Column nameContentData quality
record_idRecord IDComplete
factory_idFactory ID (F001~F005)Complete
factory_nameFactory name (1:1 correspondence with factory_id)Complete (redundant)
line_idLine number (L-A/L-B/L-C)Complete
inspection_dateInspection date (Date type)Complete
product_codeProduct codeComplete
unit_priceUnit price (yen)Complete
productionDaily productionComplete
defect_countNumber of defects (some missing due to sensor failure)30 items NULL
defect_rateDefect rate (%) (linked to defect_count)30 items NULL
inspector_idInspector ID (partially missing due to no login record)49 nulls (including duplicates)
raw_noteTest notes (not needed for analysis)Complete (not needed)
Setup: Generate the sample data (expand)
[IN: 3]
np.random.seed(42)

# ── Settings ────────────────────────────────────────────────────────────
FACTORY_IDS   = ["F001", "F002", "F003", "F004", "F005"]
FACTORY_NAMES = {
    "F001": "Tokyo factory", "F002": "Osaka factory", "F003": "Nagoya factory",
    "F004": "Yokohama factory", "F005": "Fukuoka factory",
}
FACTORY_COLORS = {
    "F001": "#4C72B0", "F002": "#DD8452", "F003": "#55A868",
    "F004": "#C44E52", "F005": "#8172B2",
}
LINE_IDS    = ["L-A", "L-B", "L-C"]
PRODUCTS    = ["EV-PCB-001", "EV-PCB-002", "EV-PCB-003"]
UNIT_PRICES = {"EV-PCB-001": 1800, "EV-PCB-002": 2400, "EV-PCB-003": 3600}
BASE_PROD   = {"F001": 480, "F002": 450, "F003": 510, "F004": 420, "F005": 380}
BASE_DR     = {"F001": 0.018, "F002": 0.015, "F003": 0.023, "F004": 0.027, "F005": 0.020}
INSPECTORS  = ["INS-001", "INS-002", "INS-003", "INS-004", "INS-005"]
N_DAYS      = 20
BASE_DATE   = datetime.date(2024, 1, 4)

# ── Record generation (5 factories x 3 lines x 20 days = 300 records)────────────────────────
rows = []
for day_idx in range(N_DAYS):
    check_date = BASE_DATE + datetime.timedelta(days=day_idx)
    for fid in FACTORY_IDS:
        for lid in LINE_IDS:
            prod_code  = str(np.random.choice(PRODUCTS))
            unit_price = UNIT_PRICES[prod_code]
            production = int(BASE_PROD[fid] * np.random.uniform(0.92, 1.08))
            dr         = BASE_DR[fid] * np.random.uniform(0.7, 1.4)
            defect_cnt = max(0, int(round(production * dr + np.random.randn() * 1.5)))
            defect_rate = round(defect_cnt / production * 100, 4)
            inspector   = str(np.random.choice(INSPECTORS))
            note_opts   = ["normal_check", "spot_check", "recheck", "", ""]
            raw_note    = str(np.random.choice(note_opts))
            rec_no = day_idx * 15 + FACTORY_IDS.index(fid) * 3 + LINE_IDS.index(lid)
            rows.append({
                "record_id":       f"REC-{rec_no:04d}",
                "factory_id":      fid,
                "factory_name":    FACTORY_NAMES[fid],
                "line_id":         lid,
                "inspection_date": check_date,
                "product_code":    prod_code,
                "unit_price":      unit_price,
                "production":      production,
                "defect_count":    defect_cnt,
                "defect_rate":     defect_rate,
                "inspector_id":    inspector,
                "raw_note":        raw_note,
            })

# ── Introducing NULL (missing sensor/login not recorded) ──────────────────────────────
null_defect_idx    = np.random.choice(len(rows), size=30, replace=False)
null_inspector_idx = np.random.choice(len(rows), size=45, replace=False)
for idx in null_defect_idx:
    rows[idx]["defect_count"] = None
    rows[idx]["defect_rate"]  = None
for idx in null_inspector_idx:
    rows[idx]["inspector_id"] = None

# ── Added duplicate records (data synchronization bug: 15) ──────────────────────────────
dup_idx = np.random.choice(len(rows), size=15, replace=False)
for i in dup_idx:
    rows.append(dict(rows[i]))

# ── Created Polars DataFrame ────────────────────────────────────────────────
df_raw = pl.DataFrame(rows)

print(f"Total number of records : {len(df_raw):,} Items (300 records + Duplication 15 )")
print(f"number of columns         : {df_raw.width} columns")
print(f"Column name         : {df_raw.columns}")
print()
print(df_raw.head(5))
[OUT: 3]
Total number of records : 315 Items (300 records + Duplication 15 )
number of columns         : 12 columns
Column name         : ['record_id', 'factory_id', 'factory_name', 'line_id', 'inspection_date', 'product_code', 'unit_price', 'production', 'defect_count', 'defect_rate', 'inspector_id', 'raw_note']

shape: (5, 12)
┌───────────┬────────────┬───────────┬─────────┬───┬───────────┬───────────┬───────────┬───────────┐
│ record_id ┆ factory_id ┆ factory_n ┆ line_id ┆ … ┆ defect_co ┆ defect_ra ┆ inspector ┆ raw_note  │
│ ---       ┆ ---        ┆ ame       ┆ ---     ┆   ┆ unt       ┆ te        ┆ _id       ┆ ---       │
│ str       ┆ str        ┆ ---       ┆ str     ┆   ┆ ---       ┆ ---       ┆ ---       ┆ str       │
│           ┆            ┆ str       ┆         ┆   ┆ i64       ┆ f64       ┆ str       ┆           │
╞═══════════╪════════════╪═══════════╪═════════╪═══╪═══════════╪═══════════╪═══════════╪═══════════╡
│ REC-0000  ┆ F001       ┆ Tokyo     ┆ L-A     ┆ … ┆ 8         ┆ 1.5936    ┆ null      ┆ recheck   │
│           ┆            ┆ factory   ┆         ┆   ┆           ┆           ┆           ┆           │
│ REC-0001  ┆ F001       ┆ Tokyo     ┆ L-B     ┆ … ┆ 13        ┆ 2.9148    ┆ INS-004   ┆ recheck   │
│           ┆            ┆ factory   ┆         ┆   ┆           ┆           ┆           ┆           │
│ REC-0002  ┆ F001       ┆ Tokyo     ┆ L-C     ┆ … ┆ 10        ┆ 2.2472    ┆ INS-002   ┆           │
│           ┆            ┆ factory   ┆         ┆   ┆           ┆           ┆           ┆           │
│ REC-0003  ┆ F002       ┆ Osaka     ┆ L-A     ┆ … ┆ 8         ┆ 1.7937    ┆ INS-003   ┆           │
│           ┆            ┆ factory   ┆         ┆   ┆           ┆           ┆           ┆           │
│ REC-0004  ┆ F002       ┆ Osaka     ┆ L-B     ┆ … ┆ 8         ┆ 1.6529    ┆ INS-001   ┆ spot_chec │
│           ┆            ┆ factory   ┆         ┆   ┆           ┆           ┆           ┆ k         │
└───────────┴────────────┴───────────┴─────────┴───┴───────────┴───────────┴───────────┴───────────┘

No.081: Select specific columns

Use in practice

There are 12 columns in the quality inspection data, but the ones used for analysis are “factory, line, date, product, production quantity, defect rate”. Often there are only 6 columns. By extracting only the necessary columns with select(), Subsequent processing becomes faster and simpler. By narrowing down the columns to be output in a report, viewers can focus on the essential information.

Approach

select() is a relational algebra operation called Projection. Reduce the memory usage of a DataFrame by reducing the number of columns, The performance of subsequent filter and group_by is also improved. When you pass the expression (pl.col("col").alias("new_name")) to select, Column selection and conversion can be done at the same time.

Check with Python

[IN: 4]
# Select only the 6 columns needed for analysis
df_select = df_raw.select([
    "factory_id",
    "line_id",
    "inspection_date",
    "product_code",
    "production",
    "defect_rate",
])

print(f"Original number of columns : {df_raw.width} columns  {df_raw.columns}")
print()
print(f"After selection   : {df_select.width} columns  {df_select.columns}")
print()
print(df_select.head(8))
print()

# select using an expression (column selection + transformation performed at the same time)
df_expr_select = df_raw.select([
    "factory_id",
    "line_id",
    (pl.col("defect_rate") / 100).alias("defect_rate_decimal"),   # % → Decimal
    pl.col("production").alias("daily_production"),
])
print("=== select using formula (select while converting defect rate to decimal) ===")
print(df_expr_select.head(5))
[OUT: 4]
Original number of columns : 12 columns  ['record_id', 'factory_id', 'factory_name', 'line_id', 'inspection_date', 'product_code', 'unit_price', 'production', 'defect_count', 'defect_rate', 'inspector_id', 'raw_note']

After selection   : 6 columns  ['factory_id', 'line_id', 'inspection_date', 'product_code', 'production', 'defect_rate']

shape: (8, 6)
┌────────────┬─────────┬─────────────────┬──────────────┬────────────┬─────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ product_code ┆ production ┆ defect_rate │
│ ---        ┆ ---     ┆ ---             ┆ ---          ┆ ---        ┆ ---         │
│ str        ┆ str     ┆ date            ┆ str          ┆ i64        ┆ f64         │
╞════════════╪═════════╪═════════════════╪══════════════╪════════════╪═════════════╡
│ F001       ┆ L-A     ┆ 2024-01-04      ┆ EV-PCB-003   ┆ 502        ┆ 1.5936      │
│ F001       ┆ L-B     ┆ 2024-01-04      ┆ EV-PCB-003   ┆ 446        ┆ 2.9148      │
│ F001       ┆ L-C     ┆ 2024-01-04      ┆ EV-PCB-002   ┆ 445        ┆ 2.2472      │
│ F002       ┆ L-A     ┆ 2024-01-04      ┆ EV-PCB-003   ┆ 446        ┆ 1.7937      │
│ F002       ┆ L-B     ┆ 2024-01-04      ┆ EV-PCB-003   ┆ 484        ┆ 1.6529      │
│ F002       ┆ L-C     ┆ 2024-01-04      ┆ EV-PCB-001   ┆ 483        ┆ null        │
│ F003       ┆ L-A     ┆ 2024-01-04      ┆ EV-PCB-001   ┆ 488        ┆ 2.2541      │
│ F003       ┆ L-B     ┆ 2024-01-04      ┆ EV-PCB-002   ┆ 523        ┆ 2.4857      │
└────────────┴─────────┴─────────────────┴──────────────┴────────────┴─────────────┘

=== select using formula (select while converting defect rate to decimal) ===
shape: (5, 4)
┌────────────┬─────────┬─────────────────────┬──────────────────┐
│ factory_id ┆ line_id ┆ defect_rate_decimal ┆ daily_production │
│ ---        ┆ ---     ┆ ---                 ┆ ---              │
│ str        ┆ str     ┆ f64                 ┆ i64              │
╞════════════╪═════════╪═════════════════════╪══════════════════╡
│ F001       ┆ L-A     ┆ 0.015936            ┆ 502              │
│ F001       ┆ L-B     ┆ 0.029148            ┆ 446              │
│ F001       ┆ L-C     ┆ 0.022472            ┆ 445              │
│ F002       ┆ L-A     ┆ 0.017937            ┆ 446              │
│ F002       ┆ L-B     ┆ 0.016529            ┆ 484              │
└────────────┴─────────┴─────────────────────┴──────────────────┘

Interpreting the results

select() reduces the original 12 columns to the six needed here. It can also apply expressions, such as dividing a percentage by 100 to obtain a proportion. Selecting only relevant columns makes later processing and reports easier to follow.


No.082: Extract lines that meet the conditions

Use in practice

“Extract the days when the defect rate exceeds 2.5%” “Check only the data of Yokohama factory (F004)” Conditional filtering is the most frequently used operation in quality control reports. filter() allows you to perform row filtering in one line, which is equivalent to the SQL clause WHERE.

Approach

filter() is a relational algebra operation called Selection. In Polars, compound conditions are written using & (AND) and | (OR). Also, you can use pl.col("col").is_null() / is_not_null() to make the presence or absence of missing values ​​a condition. For multiple conditions, be sure to enclose each condition in parentheses.

Check with Python

[IN: 5]
# Single condition: Extract rows with defect rate greater than 2.5%
df_high_dr = df_raw.filter(pl.col("defect_rate") > 2.5)
print(f"Defect rate > 2.5%: {len(df_high_dr):,} records / {len(df_raw):,} records "
      f"({len(df_high_dr)/len(df_raw)*100:.1f}%)")
print(df_high_dr.select(["factory_id", "line_id", "inspection_date",
                          "production", "defect_count", "defect_rate"]).head(5))
print()

# Composite condition: Yokohama factory (F004) and row with defect rate > 2.0%
df_f004_high = df_raw.filter(
    (pl.col("factory_id") == "F004") & (pl.col("defect_rate") > 2.0)
)
print(f"=== F004-Yokohama Katsu Defect rate > 2.0% ===")
print(f"  Number of cases: {len(df_f004_high)} records")
print(df_f004_high.select(["factory_id", "line_id", "inspection_date",
                             "production", "defect_count", "defect_rate"]).head(5))
print()

# Extracting rows containing NULL (is_null)
df_missing = df_raw.filter(pl.col("defect_count").is_null())
print(f"=== defect_count The line where is missing ===")
print(f"  Number of cases: {len(df_missing)} records")
print(df_missing.select(["factory_id", "line_id", "inspection_date",
                          "defect_count", "defect_rate", "inspector_id"]).head(5))
[OUT: 5]
Defect rate > 2.5%: 86 records / 315 records (27.3%)
shape: (5, 6)
┌────────────┬─────────┬─────────────────┬────────────┬──────────────┬─────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ production ┆ defect_count ┆ defect_rate │
│ ---        ┆ ---     ┆ ---             ┆ ---        ┆ ---          ┆ ---         │
│ str        ┆ str     ┆ date            ┆ i64        ┆ i64          ┆ f64         │
╞════════════╪═════════╪═════════════════╪════════════╪══════════════╪═════════════╡
│ F001       ┆ L-B     ┆ 2024-01-04      ┆ 446        ┆ 13           ┆ 2.9148      │
│ F004       ┆ L-A     ┆ 2024-01-04      ┆ 450        ┆ 14           ┆ 3.1111      │
│ F004       ┆ L-B     ┆ 2024-01-04      ┆ 442        ┆ 12           ┆ 2.7149      │
│ F005       ┆ L-A     ┆ 2024-01-04      ┆ 399        ┆ 11           ┆ 2.7569      │
│ F005       ┆ L-B     ┆ 2024-01-04      ┆ 389        ┆ 12           ┆ 3.0848      │
└────────────┴─────────┴─────────────────┴────────────┴──────────────┴─────────────┘

=== F004-Yokohama Katsu Defect rate > 2.0% ===
  Number of cases: 49 records
shape: (5, 6)
┌────────────┬─────────┬─────────────────┬────────────┬──────────────┬─────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ production ┆ defect_count ┆ defect_rate │
│ ---        ┆ ---     ┆ ---             ┆ ---        ┆ ---          ┆ ---         │
│ str        ┆ str     ┆ date            ┆ i64        ┆ i64          ┆ f64         │
╞════════════╪═════════╪═════════════════╪════════════╪══════════════╪═════════════╡
│ F004       ┆ L-A     ┆ 2024-01-04      ┆ 450        ┆ 14           ┆ 3.1111      │
│ F004       ┆ L-B     ┆ 2024-01-04      ┆ 442        ┆ 12           ┆ 2.7149      │
│ F004       ┆ L-A     ┆ 2024-01-05      ┆ 401        ┆ 11           ┆ 2.7431      │
│ F004       ┆ L-B     ┆ 2024-01-05      ┆ 433        ┆ 14           ┆ 3.2333      │
│ F004       ┆ L-C     ┆ 2024-01-05      ┆ 404        ┆ 14           ┆ 3.4653      │
└────────────┴─────────┴─────────────────┴────────────┴──────────────┴─────────────┘

=== defect_count The line where is missing ===
  Number of cases: 30 records
shape: (5, 6)
┌────────────┬─────────┬─────────────────┬──────────────┬─────────────┬──────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ defect_count ┆ defect_rate ┆ inspector_id │
│ ---        ┆ ---     ┆ ---             ┆ ---          ┆ ---         ┆ ---          │
│ str        ┆ str     ┆ date            ┆ i64          ┆ f64         ┆ str          │
╞════════════╪═════════╪═════════════════╪══════════════╪═════════════╪══════════════╡
│ F002       ┆ L-C     ┆ 2024-01-04      ┆ null         ┆ null        ┆ INS-001      │
│ F003       ┆ L-C     ┆ 2024-01-04      ┆ null         ┆ null        ┆ null         │
│ F005       ┆ L-C     ┆ 2024-01-06      ┆ null         ┆ null        ┆ INS-002      │
│ F003       ┆ L-C     ┆ 2024-01-07      ┆ null         ┆ null        ┆ null         │
│ F004       ┆ L-C     ┆ 2024-01-07      ┆ null         ┆ null        ┆ INS-001      │
└────────────┴─────────┴─────────────────┴──────────────┴─────────────┴──────────────┘

Interpreting the results

filter() selects rows above 2.5%, rows for a chosen factory, or rows with a missing defect count. F004 has the highest defect-probability setting in this synthetic generator, so it tends to contribute more high-rate rows. Inspect missing records before choosing a treatment.


No.083: Add column

Use in practice

From the three columns of production quantity, defective quantity, and unit price, we can calculate number of non-defective products,'' sales of non-defective products,” and “defective loss.” Adding a new KPI column is the most common process in manufacturing data analysis. with_columns() is the SQL equivalent of SELECT *, calculated_col AS name.

Approach

Pass expressions to with_columns() to add or update calculated columns. A missing defect count does not mean zero defects, so keep it as null. Good-unit counts, sales-equivalent amounts, and assumed losses also remain null for that row. Aggregate observed rows and report the excluded count.

Check with Python

[IN: 6]
# Missing counts are unknown, not zero; calculated columns remain null.
# Add KPI columns with with_columns
df_kpi = df_raw.with_columns([
    pl.col("defect_count").alias("defect_count_observed"),
    (pl.col("production") - pl.col("defect_count")).alias("good_count"),
    ((pl.col("production") - pl.col("defect_count"))
     * pl.col("unit_price")).alias("revenue"),
    (pl.col("defect_count")
     * pl.col("unit_price") * 1.3).alias("loss_amount"),    # 30% additional disposal cost
])

print(f"number of columns: {df_raw.width} columns → {df_kpi.width} Column (4 (add column)")
print()
print("=== Data after adding KPI column (first 5 items) ===")
print(df_kpi.select(["factory_id", "line_id", "production", "defect_count_observed",
                     "good_count", "revenue", "loss_amount"]).head(5))
print()

# KPI aggregation by factory (group_by + agg)
factory_kpi = (
    df_kpi
    .unique(subset=["factory_id", "line_id", "inspection_date", "product_code"],
            keep="first", maintain_order=True)
    .filter(pl.col("defect_count").is_not_null())
    .group_by("factory_id")
    .agg([
        pl.col("production").sum().alias("total_production"),
        pl.col("revenue").sum().alias("total_revenue"),
        pl.col("loss_amount").sum().alias("total_loss"),
    ])
    .sort("factory_id")
)
print("=== KPI summary by factory ===")
print(f"{'factory':<12} {'Total production count':>12} {'Total sales (yen)':>16} {'Total loss (yen)':>14}")
print("-" * 58)
for row in factory_kpi.iter_rows():
    fid, prod, revenue, loss = row
    print(f"  {FACTORY_NAMES[fid]:<10} {prod:>12,} {int(revenue):>16,} {int(loss):>14,}")

# Report excluded missing observations for each factory.
coverage = (
    df_raw.unique(subset=["record_id"], maintain_order=True)
    .group_by("factory_id")
    .agg(pl.len().alias("records"),
         pl.col("defect_count").null_count().alias("missing_defect_count"))
    .sort("factory_id")
)
print(coverage)
[OUT: 6]
number of columns: 12 columns → 16 Column (4 (add column)

=== Data after adding KPI column (first 5 items) ===
shape: (5, 7)
┌────────────┬─────────┬────────────┬───────────────────────┬────────────┬─────────┬─────────────┐
│ factory_id ┆ line_id ┆ production ┆ defect_count_observed ┆ good_count ┆ revenue ┆ loss_amount │
│ ---        ┆ ---     ┆ ---        ┆ ---                   ┆ ---        ┆ ---     ┆ ---         │
│ str        ┆ str     ┆ i64        ┆ i64                   ┆ i64        ┆ i64     ┆ f64         │
╞════════════╪═════════╪════════════╪═══════════════════════╪════════════╪═════════╪═════════════╡
│ F001       ┆ L-A     ┆ 502        ┆ 8                     ┆ 494        ┆ 1778400 ┆ 37440.0     │
│ F001       ┆ L-B     ┆ 446        ┆ 13                    ┆ 433        ┆ 1558800 ┆ 60840.0     │
│ F001       ┆ L-C     ┆ 445        ┆ 10                    ┆ 435        ┆ 1044000 ┆ 31200.0     │
│ F002       ┆ L-A     ┆ 446        ┆ 8                     ┆ 438        ┆ 1576800 ┆ 37440.0     │
│ F002       ┆ L-B     ┆ 484        ┆ 8                     ┆ 476        ┆ 1713600 ┆ 37440.0     │
└────────────┴─────────┴────────────┴───────────────────────┴────────────┴─────────┴─────────────┘

=== KPI summary by factory ===
factory      Total production count Total sales (yen) Total loss (yen)
----------------------------------------------------------
  Tokyo factory       27,104       69,133,800      1,832,220
  Osaka factory       23,342       57,328,200      1,213,680
  Nagoya factory       26,491       67,486,800      2,110,680
  Yokohama factory       22,455       57,993,000      2,215,200
  Fukuoka factory       21,692       55,947,600      1,535,820
shape: (5, 3)
┌────────────┬─────────┬──────────────────────┐
│ factory_id ┆ records ┆ missing_defect_count │
│ ---        ┆ ---     ┆ ---                  │
│ str        ┆ u32     ┆ u32                  │
╞════════════╪═════════╪══════════════════════╡
│ F001       ┆ 60      ┆ 4                    │
│ F002       ┆ 60      ┆ 8                    │
│ F003       ┆ 60      ┆ 8                    │
│ F004       ┆ 60      ┆ 7                    │
│ F005       ┆ 60      ┆ 3                    │
└────────────┴─────────┴──────────────────────┘
[IN: 7]
# Comparison bar graph of sales of non-defective products and loss of defective products by factory
fig, ax = plt.subplots(figsize=(10, 5))

fids     = factory_kpi["factory_id"].to_list()
fnames   = [FACTORY_NAMES[fid] for fid in fids]
revenues = [r / 1e6 for r in factory_kpi["total_revenue"].to_list()]
losses   = [l / 1e6 for l in factory_kpi["total_loss"].to_list()]

x     = np.arange(len(fids))
width = 0.38

ax.bar(x - width / 2, revenues, width, label="Good product sales", color="#4C72B0", alpha=0.88)
ax.bar(x + width / 2, losses,   width, label="defect loss", color="#DD8452", alpha=0.88)

ax.set_title("Good product sales/defect losses by factory (KPI column added with Polars with_columns)",
             fontsize=13, pad=10)
ax.set_xlabel("factory", fontsize=11)
ax.set_ylabel("Amount (million yen)", fontsize=11)
ax.set_xticks(x)
ax.set_xticklabels(fnames)
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda v, _: f"{v:.0f}"))
ax.legend(fontsize=10)
ax.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 7]

Good product sales/defect losses by factory (KPI column added with Polars with_columns)

Interpreting the results

After adding revenue and loss_amount, remove duplicates and summarize rows with observed defect counts by factory. The chart compares those included rows; it does not show revenue or profit for all production. Check missing-record counts by factory too. The loss factor of 1.3 is a teaching assumption.


No.084: Change column name

Use in practice

The CSV output by the system often has column names in English (defect_rate, production). There are cases where you want to convert column names to Japanese for reports. rename() is a simple operation that specifies the old name → new name in dictionary format.

Approach

rename() specifies old name → new name in dictionary format. Specifying a column name that does not exist will result in ColumnNotFoundError. The same thing can be done with select([pl.col("old").alias("new")]), rename() is suitable when you only want to change the name without having to be aware of which columns to keep or delete. In actual operation, by using “English in the code and Japanese in the output report” It can achieve both maintainability and readability.

Check with Python

[IN: 8]
# Change column names from English to Japanese (using DataFrame with KPI)
df_renamed = df_kpi.rename({
    "factory_id":          "Factory ID",
    "line_id":             "line",
    "inspection_date":     "Inspection date",
    "production":          "Daily production count",
    "defect_count_observed": "Number of defects",
    "defect_rate":         "Defect rate (%)",
    "revenue":             "Good product sales",
    "loss_amount":         "defect loss",
})

print(f"Column name before change: {df_kpi.columns}")
print()
print(f"Column name after change: {df_renamed.columns}")
print()
print("=== Data after column name change (first 5 items) ===")
print(df_renamed.select(["Factory ID", "line", "Inspection date", "Daily production count",
                          "Number of defects", "Defect rate (%)", "Good product sales", "defect loss"]).head(5))
[OUT: 8]
Column name before change: ['record_id', 'factory_id', 'factory_name', 'line_id', 'inspection_date', 'product_code', 'unit_price', 'production', 'defect_count', 'defect_rate', 'inspector_id', 'raw_note', 'defect_count_observed', 'good_count', 'revenue', 'loss_amount']

Column name after change: ['record_id', 'Factory ID', 'factory_name', 'line', 'Inspection date', 'product_code', 'unit_price', 'Daily production count', 'defect_count', 'Defect rate (%)', 'inspector_id', 'raw_note', 'Number of defects', 'good_count', 'Good product sales', 'defect loss']

=== Data after column name change (first 5 items) ===
shape: (5, 8)
┌────────────┬──────┬──────────────┬──────────────┬──────────────┬─────────────┬─────────┬─────────┐
│ Factory ID ┆ line ┆ Inspection   ┆ Daily        ┆ Number of    ┆ Defect rate ┆ Good    ┆ defect  │
│ ---        ┆ ---  ┆ date         ┆ production   ┆ defects      ┆ (%)         ┆ product ┆ loss    │
│ str        ┆ str  ┆ ---          ┆ count        ┆ ---          ┆ ---         ┆ sales   ┆ ---     │
│            ┆      ┆ date         ┆ ---          ┆ i64          ┆ f64         ┆ ---     ┆ f64     │
│            ┆      ┆              ┆ i64          ┆              ┆             ┆ i64     ┆         │
╞════════════╪══════╪══════════════╪══════════════╪══════════════╪═════════════╪═════════╪═════════╡
│ F001       ┆ L-A  ┆ 2024-01-04   ┆ 502          ┆ 8            ┆ 1.5936      ┆ 1778400 ┆ 37440.0 │
│ F001       ┆ L-B  ┆ 2024-01-04   ┆ 446          ┆ 13           ┆ 2.9148      ┆ 1558800 ┆ 60840.0 │
│ F001       ┆ L-C  ┆ 2024-01-04   ┆ 445          ┆ 10           ┆ 2.2472      ┆ 1044000 ┆ 31200.0 │
│ F002       ┆ L-A  ┆ 2024-01-04   ┆ 446          ┆ 8            ┆ 1.7937      ┆ 1576800 ┆ 37440.0 │
│ F002       ┆ L-B  ┆ 2024-01-04   ┆ 484          ┆ 8            ┆ 1.6529      ┆ 1713600 ┆ 37440.0 │
└────────────┴──────┴──────────────┴──────────────┴──────────────┴─────────────┴─────────┴─────────┘

Interpreting the results

rename() changes the specified column names and preserves their order. The example uses Japanese labels for a report. Keep names consistent for downstream scripts, and apply report-specific labels at the output stage when useful.


No.085: Delete unnecessary columns

Use in practice

factory_name (one-to-one correspondence with factory_id and redundant) and raw_note (test memo) are Not required for quality analysis. By deleting drop(), the DataFrame becomes lighter, Subsequent aggregation and visualization will be faster. It’s a good practice to sort out “which columns you really need” and remove them early on.

Approach

If you continue to retain unnecessary columns, ① increased memory usage; ② Unnecessary columns are incorrectly aggregated in group_by and join, ③ Risk of column name collision, There is a disadvantage. “Which to use: select(required columns) or drop(unnecessary columns)?” drop is better if there are many columns to leave, and select is better from a maintainability perspective if fewer columns are left.

Check with Python

[IN: 9]
# Delete two unnecessary columns
redundant_cols = ["factory_name", "raw_note"]
df_lean = df_raw.drop(redundant_cols)

print(f"Before deletion: {df_raw.width} columns  {df_raw.columns}")
print()
print(f"After deletion: {df_lean.width} columns  {df_lean.columns}")
print()
print("=== Data after removing unnecessary columns (first 3 items) ===")
print(df_lean.head(3))
print()

removed = [c for c in df_raw.columns if c not in df_lean.columns]
print(f"deleted column: {removed}")
print("→ factory_name can be restored from factory_id (redundant from normalization perspective)")
print("→ raw_note is a test memo and is not needed for actual analysis.")
[OUT: 9]
Before deletion: 12 columns  ['record_id', 'factory_id', 'factory_name', 'line_id', 'inspection_date', 'product_code', 'unit_price', 'production', 'defect_count', 'defect_rate', 'inspector_id', 'raw_note']

After deletion: 10 columns  ['record_id', 'factory_id', 'line_id', 'inspection_date', 'product_code', 'unit_price', 'production', 'defect_count', 'defect_rate', 'inspector_id']

=== Data after removing unnecessary columns (first 3 items) ===
shape: (3, 10)
┌───────────┬────────────┬─────────┬───────────┬───┬───────────┬───────────┬───────────┬───────────┐
│ record_id ┆ factory_id ┆ line_id ┆ inspectio ┆ … ┆ productio ┆ defect_co ┆ defect_ra ┆ inspector │
│ ---       ┆ ---        ┆ ---     ┆ n_date    ┆   ┆ n         ┆ unt       ┆ te        ┆ _id       │
│ str       ┆ str        ┆ str     ┆ ---       ┆   ┆ ---       ┆ ---       ┆ ---       ┆ ---       │
│           ┆            ┆         ┆ date      ┆   ┆ i64       ┆ i64       ┆ f64       ┆ str       │
╞═══════════╪════════════╪═════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪═══════════╡
│ REC-0000  ┆ F001       ┆ L-A     ┆ 2024-01-0 ┆ … ┆ 502       ┆ 8         ┆ 1.5936    ┆ null      │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
│ REC-0001  ┆ F001       ┆ L-B     ┆ 2024-01-0 ┆ … ┆ 446       ┆ 13        ┆ 2.9148    ┆ INS-004   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
│ REC-0002  ┆ F001       ┆ L-C     ┆ 2024-01-0 ┆ … ┆ 445       ┆ 10        ┆ 2.2472    ┆ INS-002   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
└───────────┴────────────┴─────────┴───────────┴───┴───────────┴───────────┴───────────┴───────────┘

deleted column: ['factory_name', 'raw_note']
→ factory_name can be restored from factory_id (redundant from normalization perspective)
→ raw_note is a test memo and is not needed for actual analysis.

Interpreting the results

Removing factory_name and raw_note reduces the table from 12 columns to 10. The factory name can be recovered from the ID mapping when needed. Later missing-value examples use this df_lean table.


No.086: Check missing values

Use in practice

Use null_count() to find the number of missing values in each column. Behavior depends on the operation: ordinary arithmetic propagates null, while aggregations such as sum and mean normally exclude missing values. Report observed and excluded counts alongside the summary.

Approach

Use null_count() to inspect missing values by column. Missing percentages alone do not determine the treatment. Investigate the reason, such as an omitted record or equipment shutdown, and the purpose of the analysis. Sensor missingness may be related to quality conditions, so do not assume it is missing completely at random (MCAR).

Check with Python

[IN: 10]
# Check missing values by column (check all columns with df_raw)
null_counts = df_raw.null_count()
n = len(df_raw)

print("=== List of missing values by column ===")
print(f"{'Column name':<22} {'Number of missing items':>8} {'Missing rate':>8}  {'Evaluation'}")
print("=" * 58)
for col in df_raw.columns:
    cnt = null_counts[col][0]
    pct = cnt / n * 100
    note = "⚠️ Processing required" if pct > 0 else "✅ Complete"
    print(f"  {col:<20} {cnt:>8,} records  {pct:>5.1f}%  {note}")

print()
print(f"Total number of records: {n:,} Items (including duplicates) 15 (including items)")
print()

# Check for rows where multiple columns are NULL at the same time
both_null = df_raw.filter(
    pl.col("defect_count").is_null() & pl.col("inspector_id").is_null()
)
print(f"defect_count and inspector_id are both NULL row of: {len(both_null)} records")
if len(both_null) > 0:
    print(both_null.select(["factory_id", "line_id", "inspection_date",
                             "defect_count", "inspector_id"]).head(5))
[OUT: 10]
=== List of missing values by column ===
Column name            Number of missing items Missing rate  Evaluation
==========================================================
  record_id                   0 records    0.0%  ✅ Complete
  factory_id                  0 records    0.0%  ✅ Complete
  factory_name                0 records    0.0%  ✅ Complete
  line_id                     0 records    0.0%  ✅ Complete
  inspection_date             0 records    0.0%  ✅ Complete
  product_code                0 records    0.0%  ✅ Complete
  unit_price                  0 records    0.0%  ✅ Complete
  production                  0 records    0.0%  ✅ Complete
  defect_count               30 records    9.5%  ⚠️ Processing required
  defect_rate                30 records    9.5%  ⚠️ Processing required
  inspector_id               49 records   15.6%  ⚠️ Processing required
  raw_note                    0 records    0.0%  ✅ Complete

Total number of records: 315 Items (including duplicates) 15 (including items)

defect_count and inspector_id are both NULL row of: 5 records
shape: (5, 5)
┌────────────┬─────────┬─────────────────┬──────────────┬──────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ defect_count ┆ inspector_id │
│ ---        ┆ ---     ┆ ---             ┆ ---          ┆ ---          │
│ str        ┆ str     ┆ date            ┆ i64          ┆ str          │
╞════════════╪═════════╪═════════════════╪══════════════╪══════════════╡
│ F003       ┆ L-C     ┆ 2024-01-04      ┆ null         ┆ null         │
│ F003       ┆ L-C     ┆ 2024-01-07      ┆ null         ┆ null         │
│ F004       ┆ L-C     ┆ 2024-01-08      ┆ null         ┆ null         │
│ F003       ┆ L-C     ┆ 2024-01-16      ┆ null         ┆ null         │
│ F002       ┆ L-B     ┆ 2024-01-17      ┆ null         ┆ null         │
└────────────┴─────────┴─────────────────┴──────────────┴──────────────┘

Interpreting the results

Among the 315 rows including duplicates, defect_count and defect_rate each have 30 nulls (9.5%), and inspector_id has 49 (15.6%). Four of the 45 missing inspector IDs in the original 300 rows also appear in the added duplicates. Five rows have both fields missing. These missing values were generated randomly and are not evidence of shutdowns or absent inspectors.


No.087: Delete missing values

Use in practice

Rows that are missing in columns essential for analysis (number of defects/defect rate) are Delete if it is unreliable even if completed. drop_nulls() deletes all rows that are missing in the specified column.

Approach

  • df.drop_nulls() — Delete all rows that are missing in any of All columns
  • df.drop_nulls(subset=["col1", "col2"]) — Delete missing rows for specified columns only

In manufacturing data, such as “Exclude records that do not record the number of defects”. It is important to use subset properly because the importance of missing data differs depending on the column. drop_nulls without subset is prone to over-delete.

Check with Python

[IN: 11]
# Delete only rows with missing defect_count (subset specification)
df_no_null_defect = df_lean.drop_nulls(subset=["defect_count"])

print(f"Before deletion: {len(df_lean):,} records")
print(f"After deletion: {len(df_no_null_defect):,} records  ({len(df_lean) - len(df_no_null_defect)} (deleted)")
print()

# Confirm that the missing inspector_id remains
null_left = df_no_null_defect.null_count()
print("=== Number of missing items after drop_nulls(subset=['defect_count']) ===")
for col in df_no_null_defect.columns:
    cnt = null_left[col][0]
    status = f"remaining {cnt} records ⚠️" if cnt > 0 else "0 items ✅"
    print(f"  {col:<22}: {status}")

print()
# Comparison with deleting all missing columns at once
df_no_null_all = df_lean.drop_nulls()
print(f"Delete all columns missing: {len(df_no_null_all):,} records")
print(f"subset designation : {len(df_no_null_defect):,} records")
print(f"  → subset By designation {len(df_no_null_defect) - len(df_no_null_all)} We were able to hold many samples.")
[OUT: 11]
Before deletion: 315 records
After deletion: 285 records  (30 (deleted)

=== Number of missing items after drop_nulls(subset=['defect_count']) ===
  record_id             : 0 items ✅
  factory_id            : 0 items ✅
  line_id               : 0 items ✅
  inspection_date       : 0 items ✅
  product_code          : 0 items ✅
  unit_price            : 0 items ✅
  production            : 0 items ✅
  defect_count          : 0 items ✅
  defect_rate           : 0 items ✅
  inspector_id          : remaining 44 records ⚠️

Delete all columns missing: 241 records
subset designation : 285 records
  → subset By designation 44 We were able to hold many samples.

Interpreting the results

Removing rows with a null defect_count leaves 285 of the 315 rows. The five rows missing both fields are removed too, leaving 44 missing inspector IDs. Calling drop_nulls() on all columns leaves 241 rows, so the subset option retains 44 more. If excluded rows are systematically different, summaries of the remaining data may be biased.


No.088: Impute missing values

Use in practice

This example labels missing inspector IDs as "Unknown". Missing defect counts remain null because their values are not known. Fill them with zero only when another record confirms that an unrecorded value means zero. Imputation does not automatically improve accuracy.

Approach

There are three main types of completion strategies:

StrategyOperationApplication Situation
Constant imputationfill_null(0), fill_null("Unknown")When the value is determined by business rules
Statistical imputationfill_null(pl.col("col").mean())When a mean-value assumption fits the purpose; check effects on variance and correlation
Completion of preceding and following valuesforward_fill(), backward_fill()When preceding and following values are valid in time series data

Manufacturing data often has different rules applied to each column.

Check with Python

[IN: 12]
# Complete missing values according to business rules (based on df_lean)
# Fill only the inspector label; retain unknown defect counts and rates.
df_filled = df_lean.with_columns([
    pl.col("inspector_id").fill_null("Unknown"),
    (pl.col("defect_count").cast(pl.Float64)
     / pl.col("production") * 100).alias("defect_rate"),
])

# Check which nulls were filled and which were deliberately retained
null_after = df_filled.null_count()
any_null = any(null_after[col][0] > 0 for col in df_filled.columns)
print(f"Missing after imputation: {'Yes' if any_null else 'None (all columns NULL zero ✅)'}")
print()

# Sample comparison before and after imputation
null_rows_before = df_lean.filter(pl.col("defect_count").is_null()).head(3)
filled_ids = null_rows_before["record_id"].to_list()
null_rows_after = df_filled.filter(pl.col("record_id").is_in(filled_ids))

print("=== Before completion (missing row sample) ===")
print(null_rows_before.select(["record_id", "factory_id", "line_id",
                                "defect_count", "defect_rate", "inspector_id"]))
print()
print("=== After filling inspector IDs (same record_id) ===")
print(null_rows_after.select(["record_id", "factory_id", "line_id",
                               "defect_count", "defect_rate", "inspector_id"]))
[OUT: 12]
Missing after imputation: Yes

=== Before completion (missing row sample) ===
shape: (3, 6)
┌───────────┬────────────┬─────────┬──────────────┬─────────────┬──────────────┐
│ record_id ┆ factory_id ┆ line_id ┆ defect_count ┆ defect_rate ┆ inspector_id │
│ ---       ┆ ---        ┆ ---     ┆ ---          ┆ ---         ┆ ---          │
│ str       ┆ str        ┆ str     ┆ i64          ┆ f64         ┆ str          │
╞═══════════╪════════════╪═════════╪══════════════╪═════════════╪══════════════╡
│ REC-0005  ┆ F002       ┆ L-C     ┆ null         ┆ null        ┆ INS-001      │
│ REC-0008  ┆ F003       ┆ L-C     ┆ null         ┆ null        ┆ null         │
│ REC-0044  ┆ F005       ┆ L-C     ┆ null         ┆ null        ┆ INS-002      │
└───────────┴────────────┴─────────┴──────────────┴─────────────┴──────────────┘

=== After filling inspector IDs (same record_id) ===
shape: (3, 6)
┌───────────┬────────────┬─────────┬──────────────┬─────────────┬──────────────┐
│ record_id ┆ factory_id ┆ line_id ┆ defect_count ┆ defect_rate ┆ inspector_id │
│ ---       ┆ ---        ┆ ---     ┆ ---          ┆ ---         ┆ ---          │
│ str       ┆ str        ┆ str     ┆ i64          ┆ f64         ┆ str          │
╞═══════════╪════════════╪═════════╪══════════════╪═════════════╪══════════════╡
│ REC-0005  ┆ F002       ┆ L-C     ┆ null         ┆ null        ┆ INS-001      │
│ REC-0008  ┆ F003       ┆ L-C     ┆ null         ┆ null        ┆ Unknown      │
│ REC-0044  ┆ F005       ┆ L-C     ┆ null         ┆ null        ┆ INS-002      │
└───────────┴────────────┴─────────┴──────────────┴─────────────┴──────────────┘

Interpreting the results

Missing inspector IDs are replaced with “Unknown.” The 30 missing defect counts and rates are retained as unobserved values. Use null_count() to distinguish fields that were filled from those deliberately left missing. Put nulls last when sorting and compare observed values in the ranking.


No.089: Sort data

Use in practice

To quickly identify “Which day, line, or factory has the highest defect rate?” Your best bet is to sort the data and look at the top. sort() is equivalent to ORDER BY in SQL, and it is also possible to sort multiple columns in one row.

Approach

  • sort("col", descending=True) — Descending order (larger values first)
  • sort(["col1", "col2"], descending=[True, False]) — Multi-column sort
  • maintain_order=True — Preserve original order of equivalence rows

Sorting can also be applied to results after aggregation (group_by.agg(...).sort("col")). The process of “automatically generating the worst ranking TOP10” in weekly/monthly quality reports is This can be achieved by combining sort().head().

Check with Python

[IN: 13]
# Sort df_filled (deficiency filled) in descending order of defect rate
df_rank_source = df_filled.unique(subset=["record_id"], maintain_order=True)
df_sorted = df_rank_source.sort("defect_rate", descending=True, nulls_last=True, maintain_order=True)

print("=== Worst ranking of defect rate TOP 10 ===")
print(df_sorted.select(["factory_id", "line_id", "inspection_date",
                         "product_code", "production", "defect_count",
                         "defect_rate"]).head(10))
print()

# Multi-column sort (factory ascending order × defect rate descending order)
df_multi_sort = df_rank_source.sort(
    ["factory_id", "defect_rate"],
    descending=[False, True],
    nulls_last=True,
    maintain_order=True,
)
print("=== Factory ascending order × Defect rate descending order (first 8 items) ===")
print(df_multi_sort.select(["factory_id", "line_id", "inspection_date",
                              "defect_rate"]).head(8))
[OUT: 13]
=== Worst ranking of defect rate TOP 10 ===
shape: (10, 7)
┌────────────┬─────────┬─────────────────┬──────────────┬────────────┬──────────────┬─────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ product_code ┆ production ┆ defect_count ┆ defect_rate │
│ ---        ┆ ---     ┆ ---             ┆ ---          ┆ ---        ┆ ---          ┆ ---         │
│ str        ┆ str     ┆ date            ┆ str          ┆ i64        ┆ i64          ┆ f64         │
╞════════════╪═════════╪═════════════════╪══════════════╪════════════╪══════════════╪═════════════╡
│ F004       ┆ L-A     ┆ 2024-01-22      ┆ EV-PCB-003   ┆ 402        ┆ 17           ┆ 4.228856    │
│ F004       ┆ L-B     ┆ 2024-01-21      ┆ EV-PCB-002   ┆ 450        ┆ 19           ┆ 4.222222    │
│ F004       ┆ L-A     ┆ 2024-01-19      ┆ EV-PCB-001   ┆ 439        ┆ 18           ┆ 4.100228    │
│ F004       ┆ L-B     ┆ 2024-01-23      ┆ EV-PCB-002   ┆ 421        ┆ 16           ┆ 3.800475    │
│ F004       ┆ L-B     ┆ 2024-01-16      ┆ EV-PCB-002   ┆ 452        ┆ 17           ┆ 3.761062    │
│ F004       ┆ L-A     ┆ 2024-01-09      ┆ EV-PCB-003   ┆ 405        ┆ 15           ┆ 3.703704    │
│ F004       ┆ L-A     ┆ 2024-01-13      ┆ EV-PCB-001   ┆ 408        ┆ 15           ┆ 3.676471    │
│ F004       ┆ L-B     ┆ 2024-01-14      ┆ EV-PCB-001   ┆ 409        ┆ 15           ┆ 3.667482    │
│ F004       ┆ L-B     ┆ 2024-01-11      ┆ EV-PCB-003   ┆ 425        ┆ 15           ┆ 3.529412    │
│ F004       ┆ L-C     ┆ 2024-01-05      ┆ EV-PCB-001   ┆ 404        ┆ 14           ┆ 3.465347    │
└────────────┴─────────┴─────────────────┴──────────────┴────────────┴──────────────┴─────────────┘

=== Factory ascending order × Defect rate descending order (first 8 items) ===
shape: (8, 4)
┌────────────┬─────────┬─────────────────┬─────────────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ defect_rate │
│ ---        ┆ ---     ┆ ---             ┆ ---         │
│ str        ┆ str     ┆ date            ┆ f64         │
╞════════════╪═════════╪═════════════════╪═════════════╡
│ F001       ┆ L-B     ┆ 2024-01-05      ┆ 3.305785    │
│ F001       ┆ L-A     ┆ 2024-01-21      ┆ 2.970297    │
│ F001       ┆ L-B     ┆ 2024-01-04      ┆ 2.914798    │
│ F001       ┆ L-A     ┆ 2024-01-07      ┆ 2.910603    │
│ F001       ┆ L-B     ┆ 2024-01-18      ┆ 2.761341    │
│ F001       ┆ L-C     ┆ 2024-01-08      ┆ 2.723735    │
│ F001       ┆ L-B     ┆ 2024-01-09      ┆ 2.579365    │
│ F001       ┆ L-A     ┆ 2024-01-16      ┆ 2.564103    │
└────────────┴─────────┴─────────────────┴─────────────┘
[IN: 14]
# Horizontal bar graph of TOP15 worst ranking defect rate
from matplotlib.patches import Patch

top15 = df_sorted.filter(pl.col("defect_rate").is_not_null()).head(15)
labels = [
    f"{fid} / {lid}  ({str(dt)[:10]})"
    for fid, lid, dt in zip(
        top15["factory_id"].to_list(),
        top15["line_id"].to_list(),
        top15["inspection_date"].to_list(),
    )
]
rates  = top15["defect_rate"].to_list()
colors = [FACTORY_COLORS[fid] for fid in top15["factory_id"].to_list()]

fig, ax = plt.subplots(figsize=(10, 7))
ax.barh(range(len(labels)), rates, color=colors, alpha=0.88)
ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels, fontsize=9)
ax.axvline(2.0, color="red", linewidth=1.5, linestyle="--", alpha=0.7)
ax.text(2.05, -0.6, "Warning line (2.0%)", color="red", fontsize=8, va="top")
ax.set_title("Worst defect rate ranking TOP15 (sorted by Polars sort)",
             fontsize=13, pad=10)
ax.set_xlabel("Defect rate (%)", fontsize=11)
ax.invert_yaxis()

legend_handles = [
    Patch(color=FACTORY_COLORS[fid], label=FACTORY_NAMES[fid])
    for fid in FACTORY_IDS
]
ax.legend(handles=legend_handles, fontsize=9, loc="lower right")
ax.grid(axis="x", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 14]

Worst defect rate ranking TOP15 (sorted by Polars sort)

Interpreting the results

The chart compares the 15 highest observed rates after removing duplicates. It shows the factory, line, and date for each record. For actual data, use the ranking to choose records for investigation and check manufacturing conditions before drawing conclusions.


No.090: Delete duplicate data

Use in practice

If the same record is registered twice due to a data synchronization bug, The total numbers of production, sales, and defects will all be counted twice. Deduplication in unique() is the final verification step in data cleansing.

Approach

  • df.unique() — Remove rows with matching all columns as duplicates
  • df.unique(subset=[...]) — Rows with matching combinations of specified columns are considered duplicates
  • keep="first" — keep first record
  • keep="last" — Keep last record
  • maintain_order=True — Keep original row order

You can define “which combination of columns is a unique key” as a business rule in advance. Affects the accuracy of duplicate detection.

Check with Python

[IN: 15]
# Duplicate record removal
n_before = len(df_filled)

df_clean = df_filled.unique(
    subset=["factory_id", "line_id", "inspection_date", "product_code"],
    keep="first",
    maintain_order=True,
)
n_after  = len(df_clean)
n_removed = n_before - n_after

print("=== Results of deduplication ===")
print(f"  Before removal: {n_before:,} records")
print(f"  After removal: {n_after:,} records")
print(f"  Number of deletions: {n_removed:,} (duplicate) {n_removed} record)")
print()

# Check for duplicate groups (verify with df_raw)
dup_check = (
    df_raw
    .group_by(["factory_id", "line_id", "inspection_date", "product_code"])
    .agg(pl.len().alias("count"))
    .filter(pl.col("count") > 1)
    .sort(["count", "factory_id", "line_id", "inspection_date", "product_code"],
          descending=[True, False, False, False, False])
)
print(f"Number of duplicate groups: {len(dup_check)} group")
if len(dup_check) > 0:
    print(dup_check.head(5))
print()

# Final DataFrame summary after cleansing is complete
null_final = df_clean.null_count()
any_null_final = any(null_final[col][0] > 0 for col in df_clean.columns)
print("=== Cleansed df_clean summary ===")
print(f"  number of lines : {len(df_clean):,} records")
print(f"  number of columns : {df_clean.width} columns")
print(f"  Missing values : {'Yes' if any_null_final else 'None (all columns NULL zero ✅)'}")
print(f"  Duplication : {n_removed} removed ✅")
print()
print(df_clean.head(5))
[OUT: 15]
=== Results of deduplication ===
  Before removal: 315 records
  After removal: 300 records
  Number of deletions: 15 (duplicate) 15 record)

Number of duplicate groups: 15 group
shape: (5, 5)
┌────────────┬─────────┬─────────────────┬──────────────┬───────┐
│ factory_id ┆ line_id ┆ inspection_date ┆ product_code ┆ count │
│ ---        ┆ ---     ┆ ---             ┆ ---          ┆ ---   │
│ str        ┆ str     ┆ date            ┆ str          ┆ u32   │
╞════════════╪═════════╪═════════════════╪══════════════╪═══════╡
│ F001       ┆ L-C     ┆ 2024-01-04      ┆ EV-PCB-002   ┆ 2     │
│ F002       ┆ L-A     ┆ 2024-01-09      ┆ EV-PCB-002   ┆ 2     │
│ F002       ┆ L-A     ┆ 2024-01-18      ┆ EV-PCB-002   ┆ 2     │
│ F002       ┆ L-B     ┆ 2024-01-14      ┆ EV-PCB-003   ┆ 2     │
│ F002       ┆ L-B     ┆ 2024-01-18      ┆ EV-PCB-001   ┆ 2     │
└────────────┴─────────┴─────────────────┴──────────────┴───────┘

=== Cleansed df_clean summary ===
  number of lines : 300 records
  number of columns : 10 columns
  Missing values : Yes
  Duplication : 15 removed ✅

shape: (5, 10)
┌───────────┬────────────┬─────────┬───────────┬───┬───────────┬───────────┬───────────┬───────────┐
│ record_id ┆ factory_id ┆ line_id ┆ inspectio ┆ … ┆ productio ┆ defect_co ┆ defect_ra ┆ inspector │
│ ---       ┆ ---        ┆ ---     ┆ n_date    ┆   ┆ n         ┆ unt       ┆ te        ┆ _id       │
│ str       ┆ str        ┆ str     ┆ ---       ┆   ┆ ---       ┆ ---       ┆ ---       ┆ ---       │
│           ┆            ┆         ┆ date      ┆   ┆ i64       ┆ i64       ┆ f64       ┆ str       │
╞═══════════╪════════════╪═════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪═══════════╡
│ REC-0000  ┆ F001       ┆ L-A     ┆ 2024-01-0 ┆ … ┆ 502       ┆ 8         ┆ 1.593625  ┆ Unknown   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
│ REC-0001  ┆ F001       ┆ L-B     ┆ 2024-01-0 ┆ … ┆ 446       ┆ 13        ┆ 2.914798  ┆ INS-004   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
│ REC-0002  ┆ F001       ┆ L-C     ┆ 2024-01-0 ┆ … ┆ 445       ┆ 10        ┆ 2.247191  ┆ INS-002   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
│ REC-0003  ┆ F002       ┆ L-A     ┆ 2024-01-0 ┆ … ┆ 446       ┆ 8         ┆ 1.793722  ┆ INS-003   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
│ REC-0004  ┆ F002       ┆ L-B     ┆ 2024-01-0 ┆ … ┆ 484       ┆ 8         ┆ 1.652893  ┆ INS-001   │
│           ┆            ┆         ┆ 4         ┆   ┆           ┆           ┆           ┆           │
└───────────┴────────────┴─────────┴───────────┴───┴───────────┴───────────┴───────────┴───────────┘

Interpreting the results

Removing 15 duplicate rows leaves df_clean with 300 rows and 10 columns. Missing inspector IDs are labeled “Unknown,” but 30 nulls remain in both defect count and defect rate. Deduplication does not recover missing observations.

State which rows are included in summaries and how many are excluded. The factory, line, date, and product key relies on this example’s assumption of one record per line per day.


Applying the exercises at work

The 10 data processing operations learned in Nos.081-090 are the backbone of the manufacturing data cleansing pipeline.

1. Standard flow of data processing

In practice, data is organized in the following order:

① select() → Narrow down to only necessary columns
② filter() → exclude unnecessary lines (for testing/outside range)
③ drop() → Delete redundant columns (normalization/unnecessary metadata)
④ null_count() → Understand the overall picture of defects
⑤ drop_nulls() or fill_null() → Process missing items according to business rules
⑥ unique() → remove duplicates
⑦ with_columns() → Add KPI columns/derived columns
⑧ rename() → Change column name for report
⑨ sort() → Check ranking and time series

2. Get even faster with Polars’ Lazy Evaluation

Use df.lazy() to build an execution plan and .collect() to run it. To optimize from the CSV-reading stage, start with pl.scan_csv(). Measure runtime and memory with the intended data and operations to assess the benefit.

3. Business rules for handling missing values

Decide which missing values to retain, which fields can use a fallback label, and which may be imputed after validation. Record the reasons. Do not turn an unobserved defect count into zero defects. Report excluded records with the analysis results.

Applying the code to your data

These are the steps to implement the Polars data processing operations learned in this chapter into the data pipeline at the manufacturing site.

Step 1: Install Polars and check existing scripts (about half a day)

uv add polars

Check compatibility with existing pandas code. Mutual conversion is possible with pl.from_pandas(df_pd) / df_pl.to_pandas().

Step 2: Quality survey of raw data (about 1 day)

Use null_count() and unique() to measure the missing rate and duplicate rate of collected data. The starting point for quality control is “understanding the quality of your data numerically.”

Step 3: Build the cleansing pipeline (about 2-3 days)

In the order inspect columns → check duplicates → define missing-data rules → fill justified fields → calculate KPIs → summarize Create a cleansing function and automatically apply it to the CSVs you receive each day. Polars’ Lazy Evaluation (df.lazy()...collect()) is fast even with large amounts of data.

Step 4: Incorporate into KPI dashboard (about 1-2 days)

Add sales/loss/defect rate KPI columns added in with_columns to Rank with sort().head() and automatically generate graphs with Matplotlib. In Chapter 10 (Aggregation, Visualization, and Mini-Analysis), we will complete this pipeline.

Summary

We will summarize what we learned in this chapter (No.081-090).

No.SkillsUtilization at manufacturing sites
081Select specific columnsReduce from 12 columns to 6 columns to speed up subsequent processing
082Extract rows that meet the conditionsDefect rate > Filtering by threshold value, specific factory, etc.
083Add columnsBatch calculation and bar graph visualization of KPI columns for number of good products, sales, and losses
084Changing column namesEnglish column names → converted to Japanese and formatted for reports
085Delete unnecessary columnsDelete redundant factory_name and test raw_note
086Check missing valuesIdentify sensor missing (9.5%) and login missing (15.6%)
087Delete missing valuesDelete only missing rows of required columns by specifying subset
088Complement missing valuesRetain missing defect counts; label missing inspector IDs as Unknown
089Sort dataGenerate the worst defect rate ranking in one line and visualize it as a horizontal bar graph
090Delete duplicate dataCompletely remove 15 duplicates of data synchronization bug with unique

In Chapter 10 (No.091-100), you will learn aggregation, visualization, and mini-analysis. Using a separate synthetic annual sales dataset, we cover group_by, dates, Matplotlib charts, and correlation.

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 apply the data preprocessing pipeline in this chapter to my company’s quality inspection data.”
  • “I want to create a system that automatically collects and cleanses data from multiple factories every day.”
  • “I can’t decide whether to use Polars or pandas”
  • “How should we standardize the rules for handling missing values and duplicates within our company?”
  • “I would like Python training to be customized and implemented for the manufacturing industry.”

Services provided

ServiceOverview
Python training for the manufacturing industryPractical training using field data (online/face-to-face)
Data quality cleansing platformAutomated pipeline construction for missing/duplicated/type conversion
Quality control dashboardAutomatic KPI aggregation, defect rate ranking, and alert visualization
DX promotion consultingConsistent support from problem resolution to implementation and establishment support

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