TExcelTAD
Home › Data Science › DS Data Preparation

DS Data Preparation

Before any analysis, data must be prepared: loaded, checked, and cleaned so that every value means what you think it means. Skipping this step is the most common reason analyses go wrong.

Riverside Bikes' stations export a daily CSV. Here is one week from the Old Bridge station, exactly as it arrived — with all of its problems. We read it from a string with io.StringIO, which behaves like a file:

python · try it yourself
import io
import pandas as pd

csv_text = """date,temp_c,rain_mm,rides,station
2024-04-01,24.1,0,150,Old Bridge
2024-04-02,15.4,0,112,old bridge
2024-04-03,26.3,,161,Old Bridge
2024-04-03,26.3,,161,Old Bridge
2024-04-04,-999,0,147,Old Bridge 
2024-04-05,6.4,0,n/a,Old Bridge
2024-04-06,29.4,0,"1,890",Old Bridge
"""

raw = pd.read_csv(io.StringIO(csv_text))
print(raw)
print()
print(raw.dtypes)
         date  temp_c  rain_mm  rides      station
0  2024-04-01    24.1      0.0    150   Old Bridge
1  2024-04-02    15.4      0.0    112   old bridge
2  2024-04-03    26.3      NaN    161   Old Bridge
3  2024-04-03    26.3      NaN    161   Old Bridge
4  2024-04-04  -999.0      0.0    147  Old Bridge
5  2024-04-05     6.4      0.0    NaN   Old Bridge
6  2024-04-06    29.4      0.0  1,890   Old Bridge

date        object
temp_c     float64
rain_mm    float64
rides       object
station     object
dtype: object

pandas already turned the blank rain value and "n/a" into NaN (it recognises common "missing" markers), but the rides column was still read as text (object) because of "1,890". We can also see a duplicate row, a -999 code that means "sensor error", and three spellings of the station name (one with a trailing space).

A preparation checklist

Step pandas tools
1. Fix types pd.to_numeric(..., errors="coerce"), pd.to_datetime
2. Recode placeholders replace(-999, np.nan) or na_values= when reading
3. Tidy text labels .str.strip(), .str.title()
4. Remove duplicates drop_duplicates()
5. Handle missing values isna(), dropna(), fillna()
6. Check ranges boolean filters, describe()

Steps 1–4: types, codes, labels and duplicates

pd.to_numeric(..., errors="coerce") turns anything that isn't a valid number into NaN ("not a number", pandas' marker for missing). Remove the thousands separator first, otherwise "1,890" would be lost too:

python · try it yourself
import io
import numpy as np
import pandas as pd

csv_text = """date,temp_c,rain_mm,rides,station
2024-04-01,24.1,0,150,Old Bridge
2024-04-02,15.4,0,112,old bridge
2024-04-03,26.3,,161,Old Bridge
2024-04-03,26.3,,161,Old Bridge
2024-04-04,-999,0,147,Old Bridge 
2024-04-05,6.4,0,n/a,Old Bridge
2024-04-06,29.4,0,"1,890",Old Bridge
"""
df = pd.read_csv(io.StringIO(csv_text))

df["date"] = pd.to_datetime(df["date"])
df["rides"] = pd.to_numeric(df["rides"].str.replace(",", ""), errors="coerce")
df["temp_c"] = df["temp_c"].replace(-999, np.nan)
df["station"] = df["station"].str.strip().str.title()
df = df.drop_duplicates()

print(df)
print()
print(df.dtypes)
print("Stations:", df["station"].unique())
        date  temp_c  rain_mm   rides     station
0 2024-04-01    24.1      0.0   150.0  Old Bridge
1 2024-04-02    15.4      0.0   112.0  Old Bridge
2 2024-04-03    26.3      NaN   161.0  Old Bridge
4 2024-04-04     NaN      0.0   147.0  Old Bridge
5 2024-04-05     6.4      0.0     NaN  Old Bridge
6 2024-04-06    29.4      0.0  1890.0  Old Bridge

date       datetime64[ns]
temp_c            float64
rain_mm           float64
rides             float64
station            object
dtype: object
Stations: ['Old Bridge']

Now every column has the right type and there is a single station name. But look at the 6 April: 1,890 rides at a station with 20 docks is not plausible — probably a typing error for 189. That's a judgement call you document, not something code can decide alone.

Steps 5–6: missing values and plausibility

isna().sum() counts missing values per column. Then decide, column by column, what to do:

  • Drop rows when the missing value is essential and rare.
  • Fill with a sensible value: 0 for rain (the gauge only reports when it rains), the median for temperature.
  • Flag suspicious values instead of silently changing them.
python · try it yourself
import io
import numpy as np
import pandas as pd

csv_text = """date,temp_c,rain_mm,rides,station
2024-04-01,24.1,0,150,Old Bridge
2024-04-02,15.4,0,112,old bridge
2024-04-03,26.3,,161,Old Bridge
2024-04-03,26.3,,161,Old Bridge
2024-04-04,-999,0,147,Old Bridge 
2024-04-05,6.4,0,n/a,Old Bridge
2024-04-06,29.4,0,"1,890",Old Bridge
"""
df = pd.read_csv(io.StringIO(csv_text), na_values=["n/a", -999], thousands=",")
df["date"] = pd.to_datetime(df["date"])
df["station"] = df["station"].str.strip().str.title()
df = df.drop_duplicates()

print(df.isna().sum())
print()

df["rain_mm"] = df["rain_mm"].fillna(0)
df["temp_c"] = df["temp_c"].fillna(df["temp_c"].median())
df["suspicious"] = df["rides"] > 20 * 10         # 20 docks, at most ~10 rentals per dock
df = df.dropna(subset=["rides"])

print(df)
date       0
temp_c     1
rain_mm    1
rides      1
station    0
dtype: int64

        date  temp_c  rain_mm   rides     station  suspicious
0 2024-04-01    24.1      0.0   150.0  Old Bridge       False
1 2024-04-02    15.4      0.0   112.0  Old Bridge       False
2 2024-04-03    26.3      0.0   161.0  Old Bridge       False
4 2024-04-04    24.1      0.0   147.0  Old Bridge       False
6 2024-04-06    29.4      0.0  1890.0  Old Bridge        True

This version moves the type fixes into read_csv itself: na_values declares the placeholder codes and thousands="," parses "1,890" correctly. Declaring such rules where the data is loaded keeps them in one visible place.

Tip: Write preparation as a script (or a function) that starts from the raw file every time. Never edit the raw data by hand — you'd lose the record of what changed.

Test yourself

What does pd.to_numeric(s, errors="coerce") do with a value like "n/a"?

  1. Raises an error
  2. Turns it into NaN
  3. Turns it into 0
  4. Leaves it as text

Why should a code like -999 be converted to NaN before computing a mean?

  1. Because pandas can't add negative numbers
  2. Because it is a placeholder for "unknown" and would drag the mean down
  3. Because NaN is faster
  4. It shouldn't — -999 is a valid temperature

Which method removes repeated identical rows?

  1. df.unique()
  2. df.drop_duplicates()
  3. df.dropna()
  4. df.distinct()