Sub topic 8
Organizing raw, interim, and processed data
This chapter assumes you can read and write basic pandas code and use Git, including .gitignore. It also assumes you have seen the repository layout from the earlier chapter, where data/ holds three subfolders: raw/, interim/, and processed/. Here you will learn what each folder is for, which rules keep them trustworthy, and how a preparation script moves data from one to the next.
Why split data into stages
A model's result depends on the code, the configuration, and the data. You can recreate code and configuration from Git. Data is harder. If you overwrite a CSV with a cleaned version, the original is gone, and you can no longer check whether the cleaning was correct.
Splitting data by processing stage solves this. Each stage has one job and one rule about who may change it. When something looks wrong in a model, you can inspect each stage in turn and find where the problem entered.
The three stages
| Folder | Contents | Who writes it | Rule |
|---|---|---|---|
| `data/raw/` | Data exactly as it was received: exports, downloads, labeled files | A person or an ingestion job, once | Never edited or overwritten |
| `data/interim/` | Partly transformed data, such as cleaned or joined tables | Code in `src/` | Safe to delete and rebuild |
| `data/processed/` | Final, model-ready tables: features and labels, train and test splits | Code in `src/` | Safe to delete and rebuild |
Raw data is read-only
Treat raw/ as an archive. If a file has bad rows, do not fix it in place. Write a cleaning step that removes or repairs the rows and saves the result to interim/. Then the fix is code that you can review, test, and rerun. A manual edit to a raw file leaves no record.
If your source is a database or an API that changes over time, save a snapshot into raw/ and note the date and the query. Otherwise you cannot get the same data again.
Interim data holds the in-between steps
Interim files exist because some transformations are slow or are worth inspecting. Examples are a cleaned table, the result of joining two sources, or text after tokenization. You can skip this folder in a small project. In a larger one, it lets you rerun only the later steps when a feature definition changes.
Processed data is what the model reads
Training code should read only from processed/. This gives the training step a single, stable input. It also means that changing a cleaning rule cannot silently change the training script, because the only link between them is a file.
The data_path: data/processed/train.csv value in configs/train.yaml follows this rule. The config names the processed file, never a raw one.
The rules, in short
- Data flows in one direction: raw, then interim, then processed. A later stage never writes to an earlier folder.
- Only code writes to
interim/andprocessed/. No manual edits. - Anything in
interim/orprocessed/can be deleted and rebuilt fromraw/plus the code and config. - Paths are not scattered through the code. Define them once, or read them from the config.
The diagram shows the flow, and the code that connects each stage.
A worked example
Create a small raw file. It has a duplicate row, a missing age, and an impossible age, which are the kinds of defects real exports contain.
mkdir -p data/raw data/interim data/processed
cat > data/raw/customers.csv <<'EOF'
id,age,income,churned
1,34,52000,0
2,45,61000,1
2,45,61000,1
3,,48000,0
4,230,75000,0
5,29,39000,1
EOFNow write the preparation step as src/my_project/data/prepare.py. The transformations are plain functions that take and return DataFrames, so they are easy to test. Only main touches the file system.
from pathlib import Path
import pandas as pd
RAW = Path("data/raw")
INTERIM = Path("data/interim")
PROCESSED = Path("data/processed")
def clean(df):
df = df.drop_duplicates()
df = df.dropna(subset=["age", "income", "churned"])
return df[df["age"].between(18, 100)]
def build_features(df):
out = df.copy()
out["income_k"] = out["income"] / 1000
return out[["age", "income_k", "churned"]]
def main():
INTERIM.mkdir(parents=True, exist_ok=True)
PROCESSED.mkdir(parents=True, exist_ok=True)
raw = pd.read_csv(RAW / "customers.csv")
cleaned = clean(raw)
cleaned.to_csv(INTERIM / "customers_clean.csv", index=False)
features = build_features(cleaned)
features.to_csv(PROCESSED / "train.csv", index=False)
print(f"raw rows: {len(raw)}, clean rows: {len(cleaned)}")
if __name__ == "__main__":
main()Run it from the project root:
python -m my_project.data.prepareThe output is raw rows: 6, clean rows: 3. The duplicate, the missing age, and the age of 230 are all gone from interim/ and processed/, and raw/customers.csv is unchanged. If you later decide that ages above 100 should be kept, you edit one line in clean, delete the derived folders, and rebuild.
Run it as a module
The command uses python -m my_project.data.prepare and not python src/my_project/data/prepare.py. This matches the cmd in the dvc.yaml from the pipeline chapter. It also means the script runs as part of the installed package, so it can import sibling modules without path hacks.
Keeping data out of Git
Git stores every version of every file forever, and it handles large binary or tabular files poorly. Keep the folder structure in Git but not the contents. A .gitignore can do this:
data/*/*
!data/*/.gitkeepThe first line ignores everything inside each stage folder. The second line re-includes an empty .gitkeep file, which you create in each folder so Git keeps the empty directories. A new teammate then clones the repository and gets the right structure.
This raises a question: if the data is not in Git, how does anyone get the same files? The next chapter covers data versioning tools. They store a small pointer file in Git and the real data in separate storage.
Common errors
- Editing raw files by hand. The fix is lost, and nobody can tell which version of the file a past model used. Write a cleaning step instead.
- Training on
interim/. The model then depends on a half-finished stage. A change to the feature step will not reach it, and results become hard to explain. - Splitting before cleaning, or cleaning after splitting. Decide where the train and test split happens and keep it in one stage. Computing statistics such as means or scalers on the full data before splitting leaks test information into training. Fit them on the training portion only.
- Hard-coded absolute paths. A path like
/home/ana/data/train.csvfails on every other machine. Use paths relative to the project root, or take them from the config. - Unstable row order. If a stage reads files in whatever order the operating system returns them, output can differ between runs. Sort file lists, and sort or index rows when order matters.
- Mixing generated and original files. If a derived file ends up in
raw/, you lose the guarantee thatraw/is the source of truth.
Naming and documenting files
Use names that say what a file is, not when you made it. customers_clean.csv is better than data_v2_final.csv. When a version matters, let the versioning tool track it and do not encode it in file names.
Add a short README.md in data/raw/ or at the top of the repository. For each raw file, record where it came from, when it was obtained, and what each column means. This is the one piece of documentation that cannot be recovered from code.
Exercise
A colleague finds that some rows in data/raw/customers.csv have negative incomes and edits the file to remove them. Why is this a problem, and what should they do instead?
Show answer
The edit changes the source of truth without any record, so the change cannot be reviewed, tested, or repeated, and earlier models can no longer be traced to the data they used. They should restore the original file and add a rule to the cleaning function in prepare.py (for example, keeping only rows where income is at least 0). The result goes to data/interim/, and the rule is then versioned in Git alongside the code.
Exercise
Training code reads data/interim/customers_clean.csv directly. Name one concrete problem with this and the change that fixes it.
Show answer
The model now depends on a stage that is not final, so a later change to the feature step (such as the incomek column) never reaches training, and the stages no longer have a clear contract. Make the feature step write data/processed/train.csv, and point datapath in configs/train.yaml at that file.