← All writing
13 min read

Data Understanding and Preparation: Turning Raw Data into Analysis-Ready Data

Part 3 of 10. Profile, validate, clean, explore, and transform raw data with Python and Pandas before analysis or machine learning.

  • Data Science
  • Python
  • Pandas
  • Data Quality
  • EDA
Data science preparation workflow from raw data through profiling, quality checks, cleaning, exploratory analysis, validation, and an analysis-ready dataset.
Preparation is an iterative engineering and analytical process—not a one-time cleanup step.

Collecting data is a milestone, not a finish line. Raw data is rarely ready for analysis or machine learning. It can contain missing values, duplicates, inconsistent formats, invalid types, unusual observations, and records that do not match the business process they are meant to describe. A dataset can also be technically clean and still be unsuitable for the question being asked.

In Part 1, we framed the decision and analytical question before choosing a model. In Part 2, we covered source discovery, extraction, ingestion, and reliable data movement. Part 3 focuses on understanding what arrived and preparing it for trustworthy analysis. The methods in this article apply across industries; healthcare claims are one illustrative dataset, not the subject of the technical discussion.

1. Start with the analytical question and data grain

Before changing a value, establish what one row represents. This is the grain of the dataset. A claims extract might contain one row per claim header, one row per claim line, one row per adjustment, or one row per member-month. Those grains answer different questions. If one claim contains five service lines, summing a claim-header amount after joining it to five lines can multiply the amount five times.

Document the unit of observation, expected uniqueness, time window, population, source system, and intended use. Identify which fields are identifiers, dates, categories, measures, and potential targets. This is also where you ask whether a field is available at the time a future prediction would be made. A field that exists in the final extract may not exist at decision time.

2. Profile the dataset before cleaning it

Profiling provides a first view of structure, completeness, cardinality, distributions, and suspicious values. Start with dimensions, schema, summary statistics, null counts, distinct counts, and duplicate counts. Treat profiling as a diagnostic, not an automatic repair instruction.

pythonExample
import pandas as pd

df = pd.read_csv("claims_data.csv")

print("Shape:", df.shape)
print(df.info())
print(df.describe(include="all"))

profile = pd.DataFrame({
    "dtype": df.dtypes.astype(str),
    "missing_count": df.isna().sum(),
    "missing_pct": (df.isna().mean() * 100).round(2),
    "distinct_values": df.nunique(dropna=True),
})
print(profile.sort_values("missing_pct", ascending=False))
A compact first-pass profile using Pandas. Expand it with source-specific rules and expected ranges.

For larger datasets, profiling may need to run in the warehouse or distributed processing engine rather than loading every row into a notebook. Approximate distinct counts, sampled distributions, and partition-level metrics can reduce cost while still identifying major issues.

3. Assess quality using explicit rules

Useful dimensions include completeness, validity, consistency, uniqueness, accuracy, and timeliness. Completeness asks whether required values are present. Validity asks whether values conform to expected formats and business rules. Consistency asks whether the same concept is represented the same way across sources. Uniqueness asks whether records match the declared grain. Accuracy asks whether values reflect the real event. Timeliness asks whether the data is fresh enough for its use.

Turn those dimensions into testable rules. Examples include a non-null business key, a date that parses successfully, a permitted status code, a non-negative quantity where the domain requires it, a start date no later than an end date, and a uniqueness test on the declared composite key. A rule should have an owner, severity, threshold, and response when it fails.

pythonExample
quality_checks = {
    "claim_id_missing": int(df["claim_id"].isna().sum()),
    "invalid_service_date": int(
        pd.to_datetime(df["service_date"], errors="coerce").isna().sum()
    ),
    "duplicate_claim_lines": int(
        df.duplicated(["claim_id", "claim_line_number"]).sum()
    ),
}

for check, failures in quality_checks.items():
    print(f"{check}: {failures}")
Example checks only. The expected key and valid-value rules must come from the dataset contract and business definition.

4. Handle missing values based on their meaning

Missingness is not one problem with one solution. A blank value can mean not collected, not applicable, unknown, withheld, delayed, or lost during ingestion. Those meanings should not be collapsed into one generic replacement without investigation.

Possible treatments include rejecting a record that lacks a required identifier, preserving an explicit unknown category, imputing a numerical feature using a training-set statistic, or retaining a missingness indicator. The decision depends on the field, the analytical question, and the process that produced the missing value. Imputing a missing payment amount or eligibility decision can manufacture information and is usually inappropriate without a defensible domain rule.

pythonExample
# Inspect missingness before choosing a treatment
missing = df.isna().mean().sort_values(ascending=False)
print((missing * 100).round(1))

# Example only: use an explicit category when absence is meaningful
df["claim_status"] = (
    df["claim_status"].astype("string").str.strip().fillna("Unknown")
)
Do not apply a blanket fillna strategy to every column. Record the reason and impact of each treatment.

5. Distinguish duplicates from legitimate repeated events

An exact duplicate row may indicate a repeated extract or ingestion retry. A repeated business identifier may be entirely valid when the grain is lower than the identifier. For example, a claim identifier can repeat across multiple claim lines. Define the expected unique key first, then test it.

pythonExample
# Exact row duplicates
exact_duplicates = df.duplicated().sum()

# Business-key duplicates at claim-line grain
claim_line_duplicates = df.duplicated(
    subset=["claim_id", "claim_line_number"], keep=False
)

print(exact_duplicates, claim_line_duplicates.sum())
Remove duplicates only after confirming they are invalid for the declared grain.

When duplicates are removed, preserve an audit count and, where appropriate, a rejected-record dataset. Silent deletion makes it difficult to explain row-count changes or reconcile the prepared dataset to its source.

6. Standardize types and values

Dates should be parsed as dates, numeric measures as numeric types, and categories normalized without erasing meaningful distinctions. Trim whitespace and standardize casing only where the domain treats those variations as equivalent. Convert invalid values with care: coercing an unparseable date to null creates a new missing value that must be measured and handled.

pythonExample
df["service_date"] = pd.to_datetime(
    df["service_date"], errors="coerce"
)

df["paid_amount"] = pd.to_numeric(
    df["paid_amount"], errors="coerce"
)

df["claim_status"] = (
    df["claim_status"].astype("string").str.strip().str.upper()
)
Type conversion should be followed by checks for newly introduced nulls and unexpected category values.

7. Investigate outliers; do not automatically delete them

An outlier is an observation that is unusual relative to a distribution or rule. It may be an error, a rare but valid event, a unit mismatch, a duplicate, or a real signal. The interquartile range (IQR) is one screening method: values below Q1 minus 1.5 times the IQR or above Q3 plus 1.5 times the IQR are flagged for review.

pythonExample
q1 = df["paid_amount"].quantile(0.25)
q3 = df["paid_amount"].quantile(0.75)
iqr = q3 - q1

lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr

outlier_candidates = df[
    (df["paid_amount"] < lower) |
    (df["paid_amount"] > upper)
]
IQR flags candidates for investigation. It is not a universal rule for deleting records.

Financial, operational, and biological data are often skewed or heavy-tailed. A legitimate high-cost claim, a rare manufacturing defect, or a major transaction can be exactly the observation the analysis needs to understand. Use domain rules, robust summaries, and visualization before deciding whether to retain, correct, cap, transform, or exclude an observation.

8. Use exploratory data analysis to ask better questions

Exploratory Data Analysis (EDA) combines summary statistics and visualizations to understand distributions, relationships, segments, and change over time. A histogram can expose skew or multiple modes. A box plot can compare spread across groups. A scatter plot can reveal nonlinear relationships or clusters. A time series can reveal seasonality, gaps, and structural changes.

Start each chart with a question. What is the distribution? Does it differ by segment? Did the metric change after a process update? Are two variables associated, and could a third variable explain the pattern? Avoid treating correlation as causation or generating charts without a decision or hypothesis to investigate.

pythonExample
import matplotlib.pyplot as plt

ax = df["paid_amount"].dropna().plot(
    kind="hist", bins=40, figsize=(8, 5),
    title="Distribution of paid amounts"
)
ax.set_xlabel("Paid amount")
ax.set_ylabel("Record count")
plt.tight_layout()
plt.show()
A simple histogram can reveal skew, multiple populations, or suspicious spikes.
Exploratory data analysis examples: distribution histogram, category counts, time trend, and feature relationship scatter plot.
Choose a visualization based on the analytical question, not on visual novelty.

9. Transform features without contaminating evaluation

Transformations can include date-part extraction, aggregation, categorical encoding, scaling, logarithms, and domain-derived features. The correct transformation depends on the algorithm and intended interpretation. Tree-based methods generally do not need the same feature scaling as distance-based or many linear methods. Categorical encoding must also respect whether categories are nominal, ordinal, or high-cardinality.

For machine learning, split the data before fitting preprocessing steps that learn from the data. Imputation values, scaling parameters, feature selection, and encoders should be fitted on the training set and then applied to validation and test data. A Scikit-learn Pipeline or ColumnTransformer can keep these operations together and reduce the risk of inconsistent transformations.

pythonExample
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric_features = ["age", "prior_visits", "paid_amount"]
categorical_features = ["region", "service_category"]

numeric_pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="median", add_indicator=True)),
    ("scaler", StandardScaler()),
])

categorical_pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="most_frequent")),
    ("encoder", OneHotEncoder(handle_unknown="ignore")),
])

preprocessor = ColumnTransformer([
    ("numeric", numeric_pipeline, numeric_features),
    ("categorical", categorical_pipeline, categorical_features),
])
Fit this preprocessor inside the training workflow, after the appropriate train/test split.

10. Prevent data leakage

Data leakage occurs when training or evaluation uses information that would not be available at the prediction point. A final claim status, a payment date, or a post-decision review outcome may reveal the target in a model that is supposed to score the claim before adjudication. A random split can also leak information when related rows from the same member, account, device, or time period appear in both training and test sets.

Define the prediction timestamp and the information cutoff. For time-dependent problems, use a chronological split. For repeated entities, consider group-aware splitting. Fit preprocessing only on training data. Keep a final test set untouched until model and pipeline decisions are complete. Leakage is not just a modeling bug; it is a mismatch between the experiment and the real decision process.

11. Make preparation reproducible and observable

A robust preparation pipeline should be versioned, repeatable, testable, and monitored. Record the source snapshot or watermark, schema version, transformation code version, row counts at each stage, missing-value rates, duplicate counts, rejected records, and output location. Data contracts and automated tests can detect schema drift before it silently changes downstream analysis.

For large or frequently refreshed data, separate raw, validated, and curated layers. Keep rejected records available for investigation. Make transformations idempotent where possible so reruns do not multiply or corrupt data. Track lineage from the prepared dataset back to the source and ingestion run. These engineering controls make a notebook result reproducible as a pipeline.

12. When is a dataset analysis-ready?

A dataset is ready when it satisfies the needs of the specific analytical task—not when every null and outlier has disappeared. The grain is documented, required fields and types are validated, quality exceptions are understood, transformations are reproducible, leakage risks are addressed, and the dataset can be traced to its sources. The target and prediction-time boundary are explicit if the next step is supervised learning.

The output may be a curated analytical table, a feature dataset, or a versioned extract for modeling. The preparation record should explain what changed, why it changed, what was excluded, and which limitations remain. That documentation is part of the analytical asset.

Conclusion

Data understanding and preparation turn collected data into a trustworthy foundation for analysis. Profiling reveals what arrived. Quality rules identify what can be relied on. Cleaning and transformation make the data usable. EDA exposes patterns and problems. Leakage-aware preprocessing makes evaluation more realistic. Reproducible pipelines make the result maintainable.

The next step is feature engineering: creating useful representations from prepared data while preserving the connection to the original decision. That will be the focus of Part 4.

References and further reading

Healthcare claims and member examples are illustrative. Real healthcare datasets may contain protected health information and must be handled under applicable privacy, security, contractual, and regulatory requirements. Use synthetic or appropriately de-identified data for demonstrations and development.

JournalMercury