Most AI project time goes into getting data ready. A practical guide to extracting, cleaning, validating and scheduling data pipelines in Python with pandas.
When a business decides to try machine learning, the conversation usually starts with models: which algorithm, which framework, which cloud. In practice, the model is rarely the hard part. The hard part is getting clean, consistent, trustworthy data to the model, and doing it again every day without someone running scripts by hand.
Consider a typical Indian retailer or distributor. Sales data sits in an ERP, payments arrive through UPI and card gateways, customer details live in a CRM, and some branches still send spreadsheets by email. Dates are in different formats, GSTINs are sometimes missing, and the same customer appears under three spellings. A model trained on that raw mix will learn the mess. A data pipeline is the repeatable process that turns it into something usable.
Stage one: extraction
Extraction means pulling data out of source systems into a place where you can work with it. Common sources and the usual Python tools are:
- Relational databases (MySQL, PostgreSQL, SQL Server): SQLAlchemy with
pandas.read_sql. - Files (CSV, Excel, JSON):
pandas.read_csv,read_excelandread_json. - APIs (payment gateways, CRMs, marketplaces): the
requestsorhttpxlibrary, with pagination and rate-limit handling.
Good habits at this stage save trouble later. Extract incrementally, using an "updated since" timestamp, rather than copying whole tables each time. Keep a raw copy of what you extracted, unchanged, so you can rerun later stages if you find a bug. And extract only the columns you need: personal data you never load is personal data you never have to protect under the DPDP Act, 2023.
Stage two: cleaning with pandas
Cleaning is where most of the effort goes. The aim is consistent types, consistent formats and no silent surprises. Here is a cleaning function for an orders extract:
import pandas as pd
def clean_orders(raw: pd.DataFrame) -> pd.DataFrame:
df = raw.copy()
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
df["order_date"] = pd.to_datetime(df["order_date"], dayfirst=True, errors="coerce")
df["amount"] = pd.to_numeric(
df["amount"].astype(str).str.replace(",", "").str.replace("₹", ""),
errors="coerce",
)
df["city"] = df["city"].str.strip().str.title()
df["payment_mode"] = df["payment_mode"].str.upper().replace({"GPAY": "UPI", "PHONEPE": "UPI"})
df = df.dropna(subset=["order_id", "order_date", "amount"])
df = df.drop_duplicates(subset="order_id", keep="last")
return df
A few things to notice. errors="coerce" turns unparseable values into missing values rather than crashing, which is useful, but it can also hide problems, so count how many rows were dropped and log it. dayfirst=True matters because Indian systems commonly write dates as DD/MM/YYYY. Removing duplicates on a business key protects against the same order being extracted twice.
Stage three: validation
Cleaning fixes what you expect. Validation catches what you did not expect. Before data moves on, check it against explicit rules:
- Schema: required columns exist and have the right types.
- Ranges: amounts are positive, dates are not in the future, quantities are whole numbers.
- Allowed values: payment mode is one of a known set; state codes are valid.
- Uniqueness and references: order IDs are unique; every order's customer ID exists in the customer table.
- Volume: today's row count is within a reasonable band of recent days.
Simple assert statements or a small validation function work for a start. As pipelines grow, libraries such as pandera (schema checks on DataFrames) or Great Expectations give you declarative rules and readable reports. The important decision is what happens on failure: stop the pipeline and alert someone, or quarantine the bad rows and continue. For training data, stopping is usually safer.
Stage four: feature preparation
Models need numerical, well-defined inputs called features. Turning clean records into features typically involves:
- Aggregation: orders per customer in the last 30 days, average basket value, days since last purchase.
- Encoding categories: converting values such as city or payment mode into numbers, for example with one-hot encoding.
- Scaling: putting numerical columns on comparable ranges for algorithms that are sensitive to scale.
- Handling missing values consistently, using rules you can explain.
Two mistakes are common. The first is data leakage: using information that would not be available at prediction time, such as including a refund flag when predicting whether an order will be refunded. The second is training-serving skew: computing features one way in a notebook and another way in production. The fix for both is to write feature logic once, in a tested module, and reuse it for training and for live predictions. scikit-learn's Pipeline and ColumnTransformer help by bundling preprocessing with the model.
Stage five: scheduling and orchestration
A pipeline that runs only when someone remembers is not a pipeline. Options, from simplest to most capable:
| Option | Good for |
|---|---|
| cron on a Linux server | One or two scripts with a fixed daily schedule. |
| Cloud schedulers and serverless jobs | Small jobs without managing a server. |
| Apache Airflow, Prefect or Dagster | Many dependent steps, retries, backfills and a monitoring UI. |
Whichever you choose, make each step idempotent: running it twice for the same date should give the same result, not double the data. Write outputs to date-partitioned locations, and make reruns overwrite rather than append.
Ongoing data quality checks
Data quality is not a one-time task. Sources change: a branch starts entering amounts in lakhs, a gateway renames a field, a new product category appears. Build monitoring into the pipeline:
- Record row counts, null rates and basic statistics for key columns on every run.
- Alert when these move sharply from their recent pattern.
- Track the distribution of model inputs over time to spot drift that may reduce model accuracy.
- Keep lineage: which raw extract and code version produced each training dataset.
These checks are unglamorous, but they are what make an AI feature trustworthy months after launch.
How NextWebGen can help
NextWebGen builds and integrates business systems such as ERP and CRM platforms, which are often the main sources for AI data pipelines. We can help you organise and expose that data cleanly, set up scheduled extraction and validation, and host the pipeline on managed servers. To start with the foundations, see our ERP system services.



