Sub topic 4
Loading data and leaving the raw copy alone
This chapter covers the step after the setup cell: reading the file into a DataFrame and protecting the original data from accidental change. It assumes you can use pandas DataFrames, run cells in Jupyter, and write basic Python functions. It also assumes you have a setup cell like the one from the previous chapter, with imports, a seed, and a data path.
Why the raw copy matters
An EDA changes your understanding of the data many times. If you overwrite the loaded data with cleaned data, you lose the ability to answer questions like "how many rows did we drop?" or "what did this column look like before we fixed it?"
Two rules keep you safe:
- Never edit the raw file on disk. Treat everything under
data/raw/as read-only. - Never modify the raw DataFrame in memory. Load it into
df_raw, and build every later version as a new object.
The rules protect you in different ways. The first protects the source of truth across sessions. The second protects it within a session, where a stray assignment in one cell can silently change what later cells see.
Keep a predictable folder layout
A simple layout makes the read-only rule easy to follow:
project/
data/
raw/ original files, never edited
processed/ outputs written by your code
notebooks/
01_eda.ipynbYour setup cell defines RAW_PATH once, so every later cell refers to the same file. If the file moves, you change one line.
Loading the file
The setup cell from the previous chapter already defined the path. Now read the file:
from pathlib import Path
import pandas as pd
RAW_PATH = Path("data/raw/orders.csv")
df_raw = pd.read_csv(RAW_PATH, parse_dates=["order_date"])
print(df_raw.shape)
df_raw.info()Three details are worth noting.
- The variable name
df_rawsignals its role. Anyone reading the notebook knows not to modify it. parse_datesconvertsorder_dateto a datetime column at load time. Without it, pandas reads dates as plain strings (theobjectdtype), and date arithmetic and time plots fail or behave oddly.print(df_raw.shape)right after loading gives you a row and column count to compare against later.
Telling pandas what the file contains
By default, read_csv guesses types by scanning the data. Guessing is convenient but can go wrong. Common problems:
| Symptom | Likely cause | Option to consider |
|---|---|---|
| An ID column loses leading zeros (`00123` becomes `123`) | Parsed as integer | `dtype={"customer_id": "string"}` |
| A numeric column shows as `object` | A stray text value such as `"n/a"` or `"-"` | `na_values=["n/a", "-"]` |
| Dates appear as strings | No date parsing requested | `parse_dates=[...]` |
| A mixed-types warning appears | Large file read in chunks with inconsistent values | `dtype=` for the column, or `low_memory=False` |
| Memory use is high | Wide integer and string defaults | `usecols=[...]`, `dtype=` with smaller types |
Here is a load that states its assumptions explicitly:
df_raw = pd.read_csv(
RAW_PATH,
parse_dates=["order_date"],
dtype={"customer_id": "string", "region": "string"},
na_values=["n/a", "-", ""],
)Declaring types makes the load step self-documenting. It also makes failures louder. If a column named in dtype or parse_dates is missing from the file, pandas raises an error instead of quietly producing something different.
Pass parse_dates only for columns you expect to be clean. If a date column contains unparseable values, pandas leaves it as strings. You then find the problem in the audit step, which is the right place for it.
Protecting `df_raw` in memory
Loading into df_raw helps only if you do not change it later. Several pandas habits modify a DataFrame in place without making it obvious.
# Risky: changes df_raw itself
df_raw["region"] = df_raw["region"].str.lower()
# Risky: a "view" may or may not share data with df_raw
subset = df_raw[df_raw["amount"] > 0]
subset["flag"] = True # may raise SettingWithCopyWarningThe second example is a classic source of confusion. Depending on the pandas version and how the subset was created, the assignment may modify the original, modify only the copy, or do nothing. In pandas 2.x with default settings the behavior is still version-dependent. In pandas 3, copy-on-write is the default, so a derived object never changes its parent. If you cannot be sure which version your teammates run, write code that behaves the same everywhere.
The safe pattern is to make an explicit copy before changing anything:
df = df_raw.copy()
df["region"] = df["region"].str.strip().str.lower()A better pattern, and the one used in this tutorial, puts the changes inside a function that returns a new DataFrame. The next chapters build on this, but here is the idea in its smallest form:
def clean_orders(df):
out = df.drop_duplicates().copy()
out["region"] = out["region"].str.strip().str.lower()
out = out[out["amount"].notna() & (out["amount"] >= 0)]
return out
df = clean_orders(df_raw)
print(f"rows kept: {len(df)} of {len(df_raw)}")The function never assigns into its argument. It calls .copy() first and works on out. The caller gets a new object, and df_raw stays exactly as it was read.
Checking that the raw copy is unchanged
You can test the promise instead of trusting it. One way is to record a fingerprint right after loading and compare it later.
import pandas as pd
raw_fingerprint = pd.util.hash_pandas_object(df_raw, index=True).sum()
# ... many cells later ...
assert pd.util.hash_pandas_object(df_raw, index=True).sum() == raw_fingerprint, \
"df_raw was modified"hash_pandas_object computes a hash for each row. Summing the hashes gives one number that changes if any value changes. A failed assertion tells you that some cell mutated df_raw. This check is cheap for modest datasets. For very large ones, compare df_raw.shape and a few summary values instead.
A lighter option is to make the DataFrame hard to change by mistake. You can do this by working only on copies, and by never assigning to columns of df_raw. A code search for df_raw[ followed by = is a quick review step.
Large files and sampling
If the file is too big to load comfortably, do not start by editing it. Options that keep the raw data intact:
usecols=[...]loads only the columns you need.nrows=100_000loads the first rows for a quick look. Note that the first rows may not represent the whole file, especially if it is sorted by date.chunksize=reads in pieces, which suits aggregation but not interactive exploration.- Convert once to a columnar format such as Parquet and save it under
data/processed/. Later loads are faster and keep column types.
If you sample, say so in a markdown cell and print the sample size. A reader who sees shape of (100000, 8) should know that is a slice and not the full dataset.
SAMPLE_ROWS = 100_000 # set to None to load everything
df_raw = pd.read_csv(RAW_PATH, parse_dates=["order_date"], nrows=SAMPLE_ROWS)
print(f"loaded {len(df_raw)} rows (sample limit: {SAMPLE_ROWS})")Keeping the limit as a named constant in the setup area means one edit switches the notebook between a fast draft mode and a full run.
Common mistakes
- Reloading under the same name after editing. If you run
df = pd.read_csv(...)and then cleandfin place, you have no raw copy. Use two names. - Chained edits on a filtered frame.
df_raw[df_raw.x > 0]["y"] = 1does not do what it appears to do. Use.locon a copy. - Writing results back to
data/raw/. Save derived files todata/processed/only. - Hard-coded absolute paths. A path like
/Users/ana/Desktop/orders.csvbreaks on any other machine. Use a path relative to the project, defined once. - Silent type guesses. Compare
df_raw.dtypesagainst what you expect before trusting any summary.
Exercises
Exercise
Why does the notebook load into df_raw and then build df with a function that starts with .copy(), instead of cleaning the loaded DataFrame directly?
Show answer
Cleaning in place destroys the original, so you could no longer compare before and after (for example, count rows dropped) or re-run cleaning from a known starting point. Starting the function with .copy() means the function never changes its input, and the caller gets a new DataFrame while df_raw stays exactly as read. It also avoids version-dependent behavior with views and SettingWithCopyWarning.
Exercise
A column customer_id contains values like 00457, but after loading, df_raw["customer_id"].head() shows 457. What happened, and how do you fix it at load time?
Show answer
pandas guessed an integer type and dropped the leading zeros. Declare the type when reading: pd.read_csv(RAW_PATH, dtype={"customer_id": "string"}). Since identifiers are labels and not quantities, they should be read as strings.