🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Data Cleaning and Preparation for Analysis › Lesson 4
TEC-DATA85-05 · Lesson 4 · 11 clock hours · lab

Standardizing Strings, Dates, and Categorical Values

Objective. Students will clean and standardize free-text strings, date formats, and categorical codes from multiple sources into a single consistent schema using pandas string methods, regular expressions, and Python's datetime module.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Why Standardization Matters

Real-world data rarely arrives clean. When a city collects permit records, 311 requests, and zoning decisions from three separate departments, each system may store the same city name as "St. Louis", "ST LOUIS", or "saint louis". Dates might appear as 04/15/2023, 2023-04-15, or "April 15, 2023" depending on which form a clerk used. Neighborhood zone codes might be "R-1", "residential_1", or simply "1" across sources. Before any analysis is meaningful, all columns must conform to a single agreed-upon schema. This lab gives you hands-on practice making that happen with Python tools you will use throughout your career.

The Reference Schema

A reference schema is the authoritative definition of what every column must look like after cleaning — the data types, allowed values, and formats. In this lab a schema sheet is provided. Always consult it first; writing code before understanding the target format wastes time and produces wrong results. Check three things for every column you clean:

1. Type — should the column be a string, integer, float, or datetime?

2. Format — for strings, is it title case, upper, or lower? For dates, is it ISO 8601 (`YYYY-MM-DD`)?

3. Allowed values — for categoricals, what is the exact list of valid codes?

Cleaning Strings with pandas

pandas string accessor (`.str`) lets you apply string operations to an entire Series at once without writing a loop. Common methods you will use:

A typical city-name cleaning sequence looks like:

```python

df['city'] = df['city'].str.strip().str.title()

```

That single line removes stray spaces and converts "ST LOUIS" and "st. louis" toward a consistent form. If spelling variants remain ("Saint Louis" vs. "St. Louis"), you will need a mapping dictionary combined with `.replace()` or `.map()`.

Regular Expressions for Validation and Extraction

A regular expression (regex) is a pattern string that describes a set of text. Python's `re` module and pandas `.str` methods both accept regex patterns. Five patterns worth memorizing:

| Target | Example pattern |

|---|---|

| US phone (basic) | `r'\(?\d{3}\)?[\s\-.]?\d{3}[\s\-.]?\d{4}'` |

| US ZIP code | `r'\b\d{5}(?:-\d{4})?\b'` |

| Email address | `r'[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}'` |

| Currency string | `r'\$?\d{1,3}(?:,\d{3})*(?:\.\d{2})?'` |

| Date fragment (MM/DD/YYYY) | `r'\d{1,2}/\d{1,2}/\d{4}'` |

When you apply a regex in pandas, `regex=True` must be set explicitly in `.str.replace()`. Always test patterns on a small sample before applying them to the full column.

Parsing and Standardizing Dates

Python's `datetime` module and `pandas.to_datetime()` handle mixed date formats. The key function is:

```python

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=False)

```

When formats are mixed across rows, pass `format='mixed'` (pandas 2.0+) or use `errors='coerce'` to convert unparseable values to `NaT` so you can inspect them separately. After parsing, output a consistent string with:

```python

df['date'] = df['date'].dt.strftime('%Y-%m-%d')

```

ISO 8601 (`YYYY-MM-DD`) is the standard format for analytical pipelines because it sorts correctly as a plain string and is unambiguous across locales.

Standardizing Categorical Codes

Categorical columns require mapping every raw value to its canonical code. Build a dictionary from the schema sheet, then apply it:

```python

zone_map = {

'R-1': 'RES_LOW', 'residential_1': 'RES_LOW', '1': 'RES_LOW',

'C-1': 'COM_GEN', 'commercial': 'COM_GEN'

}

df['zone'] = df['zone'].str.strip().str.upper().map(zone_map)

```

Values not present in the map become `NaN`. Check for those with `df['zone'].isna().sum()` and investigate before proceeding.

Validating with assert Statements and pytest

Cleaning code without validation is risky. Use assert statements inside your script to catch errors immediately:

```python

assert df['city'].str.strip().eq(df['city']).all(), "City column has leading/trailing whitespace"

assert df['date'].str.match(r'\d{4}-\d{2}-\d{2}').all(), "Date column not in YYYY-MM-DD format"

```

The provided pytest file contains 12 such assertions covering all three columns. Your cleaning script must produce a DataFrame that passes all 12 before you submit. If a test fails, read the assertion message, locate the offending rows, and fix the root cause — do not hard-code row-level overrides that only mask the problem. The code review will flag hard-coded workarounds as a non-pass.

Data Safety and Professional Practice

This dataset contains municipal records that may include personally identifiable information (PII) such as addresses and contact details. Follow your program's data handling policy:

These habits reflect industry expectations and align with data governance principles tested on credentials such as CompTIA Data+ and the Google Data Analytics Certificate.

Key terms9

Reference schemaAn authoritative specification that defines the required data type, format, and allowed values for every column in a dataset after cleaning.
pandas string accessor (.str)A pandas interface that applies string methods element-wise to an entire Series, avoiding the need for explicit Python loops.
Regular expression (regex)A pattern language used to describe, search for, validate, or transform text based on character sequences and structural rules.
ISO 8601An international standard for representing dates and times; the most common form in data work is YYYY-MM-DD, which sorts correctly as plain text.
pd.to_datetime()A pandas function that parses strings or numeric values into datetime objects, enabling date arithmetic and consistent formatting.
Categorical mappingThe process of converting raw, inconsistent category labels to a fixed set of canonical codes using a lookup dictionary and pandas .map() or .replace().
Assert statementA Python statement that raises an AssertionError if a given condition is False, used in data cleaning to validate that a column meets a specified rule.
NaT (Not a Time)The pandas missing-value sentinel for datetime columns, analogous to NaN for numeric columns; produced when a date string cannot be parsed.
errors='coerce'A parameter in pd.to_datetime() and pd.to_numeric() that converts unparseable values to NaT or NaN instead of raising an exception.
In class: Students receive a merged dataset combining three municipal data sources with inconsistent city-name spellings, mixed date formats (MM/DD/YYYY, YYYY-MM-DD, verbal), and categorical codes for neighborhood zone that differ by source; using a reference schema sheet, students write a pandas cleaning script that brings all three columns into conformance. · Regular-expression workshop: instructor presents five common regex patterns for phone numbers, ZIP codes, email addresses, currency strings, and date fragments; students adapt and apply three of them to columns in their dataset, validating results with assert statements. · Students run an automated test suite (provided pytest file with 12 assertions) against their cleaned DataFrame; they must achieve 12/12 passing tests before submitting the script.
Materials: Merged municipal CSV (3 sources), reference schema sheet, Jupyter Lab, pandas, re module, Python datetime, pytest, instructor-prepared test suite
Check: Automated pytest suite must show 12/12 passing assertions (100 % required on automated tests); instructor spot-checks regex logic in code review — overall pass is 12/12 tests plus no hard-coded workarounds flagged in review.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data preparation and transformation
1. A city-name column contains the values 'NEW YORK', 'new york', and ' New York '. Which pandas expression will produce a uniform 'New York' in every row?
Data cleaning and quality
2. You call pd.to_datetime(df['date'], errors='coerce') and then check df['date'].isna().sum(), which returns 47. What does this tell you?
Data preparation and transformation
3. Which date format string produces output conforming to ISO 8601 when used with Series.dt.strftime()?
Data cleaning and quality
4. After applying a zone mapping dictionary with df['zone'].map(zone_map), several rows contain NaN. What is the most appropriate next step?
Data validation and testing
5. A student uses the following assert statement: assert df['zip'].str.match(r'\b\d{5}(?:-\d{4})?\b').all(). The assertion fails. What is the most likely cause?
Data preparation and transformation
6. Which of the following is the correct reason to prefer ISO 8601 (YYYY-MM-DD) over MM/DD/YYYY in an analytical pipeline?
Data cleaning and quality
7. A pytest test suite returns 11 passing and 1 failing assertion. The failing test checks that no leading or trailing whitespace exists in the 'city' column. A classmate suggests adding city = city.strip() only to the three specific rows that failed the test. Why is this approach flagged as a hard-coded workaround?
Data governance and ethics
8. You are cleaning a column that contains municipal addresses and phone numbers from a public dataset provided for class exercises. Which data handling practice is most consistent with professional data governance standards?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.