id stringlengths 7 7 | problem_description stringlengths 87 211 | dirty_example stringlengths 31 237 | language stringclasses 3
values | library stringclasses 6
values | cleaning_code stringlengths 55 489 | explanation stringlengths 111 211 | issue_type stringclasses 10
values | difficulty stringclasses 3
values | split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|
DCR0014 | Phone numbers are stored in multiple formats: '(555) 123-4567', '555-123-4567', '5551234567', '+15551234567'. Normalise to E.164 format '+1XXXXXXXXXX' for US numbers. | contact_id,phone
1,(555) 123-4567
2,555-123-4567
3,5551234567
4,+15551234567 | Python | pandas | import pandas as pd
import re
def to_e164(phone: str) -> str:
digits = re.sub(r"\D", "", str(phone))
if digits.startswith("1") and len(digits) == 11:
return f"+{digits}"
if len(digits) == 10:
return f"+1{digits}"
return phone # unrecognised — leave as-is
df = pd.read_csv("contacts.csv... | Stripping non-digit characters first and then branching on length handles all common US formats reliably without a complex regex. | string_normalization | intermediate | train |
DCR0085 | A 'url' column has URLs with and without trailing slashes (e.g. 'https://example.com' vs 'https://example.com/'). Normalise by stripping trailing slashes. | page_id,url
1,https://example.com/
2,https://example.com/about
3,https://example.com/blog/ | Python | pandas | import pandas as pd
df = pd.read_csv("pages.csv")
df["url"] = df["url"].str.rstrip("/")
| str.rstrip('/') removes one or more trailing slashes; it correctly leaves internal slashes (like in paths) untouched. | string_normalization | beginner | train |
DCR0111 | A 'transactions' table has negative amounts that should not exist (all transactions must be positive). Identify them and set to NULL pending review. | tx_id | amount | type
------+--------+------
1 | 150.00 | credit
2 | -50.00 | debit
3 | 200.00 | credit | SQL | PostgreSQL | -- Identify violations
SELECT tx_id, amount FROM transactions WHERE amount < 0;
-- Nullify pending review
UPDATE transactions
SET amount = NULL
WHERE amount < 0;
| Selecting before updating provides an audit log of what changed; setting to NULL (rather than deleting) preserves the row for review while making the invalid value explicit. | validation | beginner | train |
DCR0078 | A Polars DataFrame has Z-score outliers (abs(z) > 3) in a 'value' column. Replace them with null. | id,value
1,10.2
2,10.8
3,250.0
4,10.5
5,9.9 | Python | polars | import polars as pl
df = pl.read_csv("measurements.csv")
mean = df["value"].mean()
std = df["value"].std()
df = df.with_columns(
pl.when((pl.col("value") - mean).abs() / std > 3)
.then(None)
.otherwise(pl.col("value"))
.alias("value")
)
| Polars when/then/otherwise is the vectorised conditional expression; passing None to then() produces a null in the output column, preserving the row while marking the value invalid. | outlier_handling | intermediate | train |
DCR0002 | A survey dataset has a 'score' column that is missing for ~30 % of rows. Impute each missing score with the median score of the same 'age_group'. | respondent_id,age_group,score
1,18-24,7
2,18-24,
3,25-34,5
4,25-34, | Python | pandas | import pandas as pd
df = pd.read_csv("survey.csv")
df["score"] = df.groupby("age_group")["score"].transform(
lambda s: s.fillna(s.median())
)
| groupby + transform keeps the DataFrame index intact while broadcasting the group median back to every row, so missing scores get group-specific medians rather than a global value. | missing_values | intermediate | train |
DCR0071 | An R transactions data frame has a 'status' column that should only contain 'pending', 'completed', or 'cancelled'. Flag invalid rows. | tx_id,amount,status
1,100,completed
2,50,PENDING
3,200,failed
4,75,cancelled | R | dplyr | library(dplyr)
library(readr)
VALID <- c("pending", "completed", "cancelled")
df <- read_csv("transactions.csv") |>
mutate(status_norm = tolower(trimws(status)),
status_valid = status_norm %in% VALID)
# View violations
filter(df, !status_valid)
| Normalising to lowercase before the set-membership check catches case variants; a separate 'status_valid' flag preserves the original value while marking violations. | validation | beginner | train |
DCR0038 | A sales DataFrame has referential integrity requirements: every 'product_id' must exist in the products reference table. Identify and remove orphaned rows. | sale_id,product_id,amount
1,P001,50
2,P999,30
3,P002,120
4,P888,15 | Python | pandas | import pandas as pd
sales = pd.read_csv("sales.csv")
products = pd.read_csv("products.csv")
valid_ids = set(products["product_id"])
orphaned = sales[~sales["product_id"].isin(valid_ids)]
print(f"{len(orphaned)} orphaned sales rows: {orphaned['product_id'].tolist()}")
sales = sales[sales["product_id"].isin(valid_ids)]... | Using a set for valid_ids makes isin() O(1) per lookup; printing orphaned IDs before removal gives a clear audit trail of what was discarded and why. | validation | intermediate | train |
DCR0072 | An R data frame imported from Excel has messy column names (spaces, special chars). Rename them to clean snake_case with janitor. | First Name,Last Name,Phone #,E-Mail Address
Alice,Smith,5551234567,alice@example.com | R | dplyr | library(readr)
library(janitor)
df <- read_csv("contacts.csv") |>
janitor::clean_names() # converts to snake_case automatically
| janitor::clean_names() handles spaces, special characters, duplicate names, and mixed case in one call — the idiomatic R approach vs. manual rename_with(). | column_renaming | beginner | train |
DCR0062 | An R survey data frame has an 'income' column with NA for some respondents. Impute missing values with the median income grouped by 'education_level'. | respondent_id,education_level,income
1,bachelor,55000
2,bachelor,NA
3,master,80000
4,master,NA | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("survey.csv") |>
group_by(education_level) |>
mutate(income = ifelse(is.na(income),
median(income, na.rm = TRUE),
income)) |>
ungroup()
| group_by + mutate broadcasts the group median back to each row; na.rm=TRUE computes the median from non-missing group members; ungroup() removes the grouping for downstream operations. | missing_values | intermediate | train |
DCR0044 | A 'products' table stores 'price' as NUMERIC but a downstream system needs it as INTEGER cents (multiplied by 100, rounded). Create a view exposing the integer price. | product_id | price
-----------+-------
1 | 9.99
2 | 14.50
3 | 0.99 | SQL | PostgreSQL | CREATE OR REPLACE VIEW products_cents AS
SELECT
product_id,
ROUND(price * 100)::INTEGER AS price_cents
FROM products;
| ROUND before casting to INTEGER avoids floating-point truncation errors (9.99 * 100 = 998.9999... without ROUND); a view avoids mutating source data. | type_conversion | beginner | train |
DCR0023 | A log column 'logged_at' has timestamps like '2024-01-15T08:30:00.123456Z'. Parse and extract separate 'date' and 'hour' columns for partitioning. | log_id,logged_at
1,2024-01-15T08:30:00.123456Z
2,2024-01-15T14:05:22.000000Z
3,2024-01-16T01:12:45.987654Z | Python | pandas | import pandas as pd
df = pd.read_csv("logs.csv")
df["logged_at"] = pd.to_datetime(df["logged_at"], utc=True)
df["date"] = df["logged_at"].dt.date
df["hour"] = df["logged_at"].dt.hour
| .dt accessor exposes datetime components as vectorised operations; extracting date and hour into separate columns avoids repeated string manipulation downstream. | date_parsing | beginner | train |
DCR0048 | A 'addresses' table has leading and trailing whitespace in the 'street' column from user input. Remove it. | id | street
---+------------------
1 | 123 Main St
2 | 456 Oak Ave
3 | 789 Pine Rd | SQL | PostgreSQL | UPDATE addresses
SET street = TRIM(street)
WHERE street <> TRIM(street);
| TRIM() removes both leading and trailing whitespace; the WHERE clause avoids touching rows that are already clean, making the update idempotent. | string_normalization | beginner | train |
DCR0066 | An R contacts data frame has duplicate 'email' values from multiple import runs. Keep only the most recently created record per email. | id,email,created_at
1,alice@example.com,2024-01-01
2,alice@example.com,2024-02-01
3,bob@example.com,2024-01-15 | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("contacts.csv") |>
group_by(email) |>
slice_max(created_at, n = 1, with_ties = FALSE) |>
ungroup()
| group_by + slice_max keeps only the row with the maximum created_at per email group; with_ties=FALSE ensures exactly one row per group even on ties. | deduplication | intermediate | train |
DCR0020 | A measurements DataFrame has outliers identifiable via the IQR fence method. Remove rows where 'value' lies outside [Q1 - 1.5*IQR, Q3 + 1.5*IQR]. | sample_id,value
1,10.2
2,10.8
3,250.0
4,10.5
5,11.1 | Python | pandas | import pandas as pd
df = pd.read_csv("measurements.csv")
q1 = df["value"].quantile(0.25)
q3 = df["value"].quantile(0.75)
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
df = df[df["value"].between(lower, upper)]
| The Tukey fence (Q1−1.5*IQR, Q3+1.5*IQR) is a distribution-free outlier criterion robust to skewed data; between() produces a boolean mask for clean filtering. | outlier_handling | intermediate | train |
DCR0076 | A large Polars DataFrame has duplicate rows. Deduplicate keeping the first occurrence, operating in lazy mode for memory efficiency. | id,name,email
1,Alice,alice@example.com
1,Alice,alice@example.com
2,Bob,bob@example.com | Python | polars | import polars as pl
df = (
pl.scan_csv("users.csv")
.unique(keep="first")
.collect()
)
| Polars unique() in lazy mode (via scan_csv) deduplicates without loading all data into eager memory first; keep='first' matches pandas semantics. | deduplication | intermediate | train |
DCR0063 | An R data frame has a 'price' column loaded as character because of dollar signs ('$12.50'). Strip the symbol and convert to numeric. | product,price
Widget,$12.50
Gadget,$9.99
Tool,$45.00 | R | dplyr | library(dplyr)
library(readr)
library(stringr)
df <- read_csv("products.csv") |>
mutate(price = as.numeric(str_remove(price, "\\$")))
| str_remove() (stringr) removes the first occurrence of the dollar sign; as.numeric() then converts the clean string; the double-escaped backslash is needed in R strings. | type_conversion | beginner | train |
DCR0031 | A wide DataFrame has year columns ('2021', '2022', '2023') that should be melted into a long format with 'year' and 'value' columns. | region,2021,2022,2023
North,100,110,115
South,90,95,102
East,80,88,94 | Python | pandas | import pandas as pd
df = pd.read_csv("regions.csv")
df = df.melt(
id_vars=["region"],
var_name="year",
value_name="value"
)
df["year"] = df["year"].astype(int)
| melt() pivots the wide format to long format; var_name captures the column headers as the 'year' variable; casting year to int makes it numeric for filtering and plotting. | structural_issues | beginner | train |
DCR0056 | A 'users' table has a CHECK constraint that 'age' must be between 0 and 120. Find existing rows that violate this before adding the constraint. | user_id | age
--------+----
1 | 25
2 | -5
3 | 130
4 | 42 | SQL | PostgreSQL | -- 1. Find violations before adding the constraint
SELECT user_id, age
FROM users
WHERE age NOT BETWEEN 0 AND 120;
-- 2. Fix violations
UPDATE users SET age = NULL WHERE age NOT BETWEEN 0 AND 120;
-- 3. Now safely add the constraint
ALTER TABLE users ADD CONSTRAINT chk_age CHECK (age BETWEEN 0 AND 120);
| Always audit violations before adding a CHECK constraint; fixing them first prevents the ALTER TABLE from failing; NULL is the appropriate placeholder until valid data is obtained. | validation | intermediate | train |
DCR0061 | An R data frame loaded from CSV has NA values in a 'revenue' column. Replace all NAs with 0. | order_id,revenue
1,150
2,NA
3,220.5 | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("orders.csv")
df <- df |> mutate(revenue = replace_na(revenue, 0))
| tidyr::replace_na() (imported via tidyr, available in the tidyverse) is more readable than ifelse(is.na(x), 0, x) and works inside mutate() seamlessly. | missing_values | beginner | train |
DCR0012 | A product catalog has duplicate SKUs because the same item was imported from two suppliers. Keep only the supplier with the lower price. | sku,supplier,price
P001,SupA,19.99
P001,SupB,17.50
P002,SupA,45.00
P002,SupB,46.00 | Python | pandas | import pandas as pd
df = pd.read_csv("catalog.csv")
df = (
df.sort_values("price", ascending=True)
.drop_duplicates(subset=["sku"], keep="first")
.reset_index(drop=True)
)
| Sorting by price ascending before deduplication ensures the cheapest supplier row is the one kept for each SKU. | deduplication | beginner | train |
DCR0073 | An R data frame has 'timestamp' stored as Unix epoch integers. Convert to POSIXct (UTC) and format as 'YYYY-MM-DD HH:MM:SS'. | session_id,timestamp
1,1700000000
2,1700086400 | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("sessions.csv") |>
mutate(
ts_utc = as.POSIXct(timestamp, origin = "1970-01-01", tz = "UTC"),
ts_str = format(ts_utc, "%Y-%m-%d %H:%M:%S")
)
| as.POSIXct with origin='1970-01-01' interprets the integer as seconds since the Unix epoch; tz='UTC' prevents local timezone ambiguity; format() produces a human-readable string. | date_parsing | beginner | train |
DCR0049 | A 'products' table has free-text 'category' values with inconsistent hyphenation: 'hand-made', 'handmade', 'hand made'. Normalise all three to 'handmade'. | product_id | category
-----------+-----------
1 | hand-made
2 | handmade
3 | hand made | SQL | PostgreSQL | UPDATE products
SET category = 'handmade'
WHERE LOWER(REGEXP_REPLACE(category, '[- ]', '', 'g')) = 'handmade';
| REGEXP_REPLACE removes hyphens and spaces before comparison, so all three variants match; updating only those rows leaves other categories untouched. | string_normalization | intermediate | train |
DCR0005 | A price column was imported as strings with currency symbols and commas (e.g. '$1,250.00'). Convert it to float. | product,price
Widget,$1,250.00
Gadget,$89.99
Doohickey,$14,000.50 | Python | pandas | import pandas as pd
df = pd.read_csv("products.csv")
df["price"] = (
df["price"]
.str.replace(r"[\$,]", "", regex=True)
.astype(float)
)
| str.replace with a character-class regex strips $ and , in one pass before astype(float) converts the clean string to a numeric type. | type_conversion | beginner | train |
DCR0001 | A CSV of customer orders has a numeric 'revenue' column where missing values were exported as the string 'N/A'. Pandas reads them as object dtype. Fill the missing values with 0 and cast to float. | order_id,customer,revenue
1,Alice,150.00
2,Bob,N/A
3,Carol,220.50 | Python | pandas | import pandas as pd
df = pd.read_csv("orders.csv")
df["revenue"] = (
df["revenue"]
.replace("N/A", pd.NA)
.astype(float)
.fillna(0.0)
)
| replace() converts the sentinel string to pd.NA, astype(float) reinterprets the series, and fillna(0.0) substitutes the actual missing entries. | missing_values | beginner | train |
DCR0100 | After pd.merge(), overlapping non-key column names got suffixed with '_x' (left) and '_y' (right). Programmatically rename all '_x' columns to '_source' and '_y' to '_target'. | user_id,score_x,rank_x,score_y,rank_y
1,85,3,90,1
2,70,5,75,4 | Python | pandas | import pandas as pd
df = pd.read_csv("merged.csv")
df = df.rename(columns=lambda c: c.replace("_x", "_source").replace("_y", "_target"))
| Passing a function to rename() applies it to every column name; chained replace() handles both suffixes in one sweep without a dict that must enumerate every column. | column_renaming | beginner | train |
DCR0004 | A time-series sensor DataFrame has gaps (missing timestamps). Forward-fill readings for up to 3 consecutive missing periods, then back-fill any remaining NaN at the start. | timestamp,temperature
2024-01-01 00:00,21.3
2024-01-01 00:05,
2024-01-01 00:10,
2024-01-01 00:15,21.8 | Python | pandas | import pandas as pd
df = pd.read_csv("sensors.csv", parse_dates=["timestamp"])
df = df.set_index("timestamp").sort_index()
df["temperature"] = (
df["temperature"]
.ffill(limit=3)
.bfill()
)
| ffill(limit=3) propagates the last known reading for at most 3 steps, handling short outages without distorting longer gaps; bfill() covers any leading NaNs. | missing_values | intermediate | train |
DCR0065 | An R data frame has exact duplicate rows from a join. Remove all duplicates using dplyr. | user_id,email,name
1,alice@example.com,Alice
1,alice@example.com,Alice
2,bob@example.com,Bob | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("users.csv") |>
distinct()
| distinct() with no arguments removes rows that are identical across all columns; it is the dplyr equivalent of pandas drop_duplicates(). | deduplication | beginner | train |
DCR0058 | A PostgreSQL table has a column named 'order' which conflicts with a reserved keyword. Rename it to 'sort_order' without dropping data. | id | order | priority
---+-------+---------
1 | 3 | high
2 | 1 | low | SQL | PostgreSQL | ALTER TABLE items RENAME COLUMN "order" TO sort_order;
| ALTER TABLE ... RENAME COLUMN is the safe DDL for renaming without data movement; quoting 'order' with double quotes escapes the reserved keyword during the rename. | column_renaming | beginner | train |
DCR0122 | A Polars DataFrame has a 'price' column with nulls. Fill nulls with the median price per 'category' group. | id,category,price
1,A,10.0
2,A,null
3,B,20.0
4,B,null
5,B,22.0 | Python | polars | import polars as pl
df = pl.read_csv("products.csv")
df = df.with_columns(
pl.col("price").fill_null(
pl.col("price").median().over("category")
)
)
| Polars .over('category') computes a window aggregation (median per category) and broadcasts it back to each row — equivalent to pandas groupby transform but as a single expression. | missing_values | intermediate | train |
DCR0007 | A DataFrame has an 'age' column stored as float64 with values like 25.0, 30.0. Convert to nullable integer (Int64) to save memory and allow pd.NA. | name,age
Alice,25.0
Bob,
Carol,30.0 | Python | pandas | import pandas as pd
df = pd.read_csv("people.csv")
df["age"] = df["age"].astype("Int64") # capital-I nullable integer
| pandas 'Int64' (capital I) is a nullable integer extension type that can hold pd.NA, unlike numpy int64 which cannot represent missing values. | type_conversion | beginner | train |
DCR0035 | An email column should contain only valid addresses. Flag rows with malformed emails by adding an 'email_valid' boolean column. | user_id,email
1,alice@example.com
2,not-an-email
3,bob@
4,carol@example.org | Python | pandas | import pandas as pd
import re
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
df = pd.read_csv("users.csv")
df["email_valid"] = df["email"].map(
lambda e: bool(EMAIL_RE.match(str(e)))
)
| A pragmatic regex catches the most common structural failures (missing @, missing domain, trailing dot) without the complexity of RFC 5321 full compliance. | validation | beginner | train |
DCR0036 | A transactions DataFrame has a 'status' column that should only contain 'pending', 'completed', or 'cancelled'. Assert this constraint and print any violations. | tx_id,amount,status
1,100,completed
2,50,PENDING
3,200,cancelled
4,75,failed | Python | pandas | import pandas as pd
VALID_STATUSES = {"pending", "completed", "cancelled"}
df = pd.read_csv("transactions.csv")
df["status"] = df["status"].str.lower().str.strip()
invalid = df[~df["status"].isin(VALID_STATUSES)]
if not invalid.empty:
print(f"Found {len(invalid)} invalid rows:\n{invalid}")
df = df[df["status"... | Normalising case first catches 'PENDING' vs 'pending'; the isin() check then identifies true violations; printing them before dropping preserves observability. | validation | beginner | train |
DCR0077 | A Polars DataFrame 'created_at' column is stored as a string in ISO 8601 format. Parse it to Polars Datetime dtype. | id,created_at
1,2024-03-15T10:30:00
2,2024-01-01T00:00:00 | Python | polars | import polars as pl
df = pl.read_csv("records.csv")
df = df.with_columns(
pl.col("created_at")
.str.strptime(pl.Datetime, "%Y-%m-%dT%H:%M:%S")
)
| Polars str.strptime() with an explicit format string is faster than inference; the result is a native Polars Datetime column that supports efficient temporal operations. | date_parsing | beginner | train |
DCR0011 | An events log has duplicate event IDs but different timestamps — the later timestamp is the correct retry event. Keep only the row with the maximum timestamp per event_id. | event_id,user_id,timestamp,status
EV1,U1,2024-01-01 10:00,pending
EV1,U1,2024-01-01 10:05,success
EV2,U2,2024-01-01 11:00,success | Python | pandas | import pandas as pd
df = pd.read_csv("events.csv", parse_dates=["timestamp"])
df = (
df.sort_values("timestamp", ascending=False)
.drop_duplicates(subset=["event_id"], keep="first")
.sort_values("event_id")
.reset_index(drop=True)
)
| Sorting descending by timestamp before drop_duplicates makes 'first' equivalent to 'latest'; the final sort restores natural ordering. | deduplication | intermediate | train |
DCR0128 | A DataFrame has several numeric columns on very different scales. Min-max normalise all numeric columns to [0, 1] in one pass. | id,age,income,score
1,25,50000,85
2,40,120000,92
3,35,75000,78 | Python | pandas | import pandas as pd
df = pd.read_csv("features.csv")
num_cols = df.select_dtypes(include="number").columns.difference(["id"])
df[num_cols] = (df[num_cols] - df[num_cols].min()) / (df[num_cols].max() - df[num_cols].min())
| select_dtypes selects numeric columns dynamically; broadcasting subtraction and division applies min-max scaling to all columns simultaneously without a loop. | type_conversion | intermediate | train |
DCR0059 | A view references columns with legacy snake_case names but the application now expects camelCase. Create a compatibility view that renames them. | -- legacy_table columns: first_name, last_name, phone_number | SQL | PostgreSQL | CREATE OR REPLACE VIEW users_camel AS
SELECT
first_name AS "firstName",
last_name AS "lastName",
phone_number AS "phoneNumber"
FROM legacy_table;
| A view with column aliases decouples the physical schema from the API contract; quoting the aliases with double quotes preserves camelCase since PostgreSQL folds unquoted identifiers to lowercase. | column_renaming | beginner | train |
DCR0103 | A PostgreSQL 'sales' table has a 'month' column stored as an integer (1-12) and a 'year' column. Combine them into a proper DATE (first of the month). | sale_id | year | month | revenue
--------+------+-------+--------
1 | 2024 | 1 | 5000
2 | 2024 | 3 | 7500 | SQL | PostgreSQL | ALTER TABLE sales ADD COLUMN sale_date DATE;
UPDATE sales
SET sale_date = MAKE_DATE(year, month, 1);
| MAKE_DATE(year, month, day) constructs a DATE from integer parts cleanly; using day=1 pins each record to the first of the month, a natural convention for monthly aggregations. | date_parsing | beginner | train |
DCR0025 | A CSV exported from a legacy Windows system uses Windows-1252 encoding. Reading it with the default UTF-8 encoding raises UnicodeDecodeError. Load it correctly. | name,description
Café,Hot drinks
Naïve,Inexperienced | Python | pandas | import pandas as pd
df = pd.read_csv("legacy.csv", encoding="windows-1252")
# Re-save as UTF-8
df.to_csv("legacy_utf8.csv", index=False, encoding="utf-8")
| Specifying encoding='windows-1252' tells pandas the byte interpretation; re-saving as UTF-8 normalises the file for all future consumers. | encoding_issues | beginner | train |
DCR0017 | A customer name column has extra internal whitespace (e.g. 'Alice Smith', 'Bob Jones'). Collapse multiple spaces to a single space. | id,full_name
1,Alice Smith
2,Bob Jones
3,Carol Davis | Python | pandas | import pandas as pd
df = pd.read_csv("customers.csv")
df["full_name"] = df["full_name"].str.split().str.join(" ")
| str.split() without arguments splits on any whitespace run; str.join(' ') reassembles tokens with exactly one space, handling tabs and mixed whitespace too. | string_normalization | beginner | train |
DCR0099 | A DataFrame has numbered columns ('0', '1', '2') from a CSV with no header. Rename them to meaningful names from a provided list. | 0,1,2
1,Alice,95000
2,Bob,72000 | Python | pandas | import pandas as pd
COLUMN_NAMES = ["emp_id", "name", "salary"]
df = pd.read_csv("data.csv", header=None)
df.columns = COLUMN_NAMES
| header=None prevents pandas from using the first data row as headers; assigning a list to df.columns renames all columns in position order. | column_renaming | beginner | train |
DCR0051 | A 'sessions' table has 'started_at' stored as epoch milliseconds (BIGINT). Convert to TIMESTAMPTZ. | session_id | started_at
-----------+-------------
1 | 1700000000000
2 | 1700086400000 | SQL | PostgreSQL | SELECT
session_id,
TO_TIMESTAMP(started_at / 1000.0) AT TIME ZONE 'UTC' AS started_at_ts
FROM sessions;
| Dividing by 1000.0 converts milliseconds to seconds (keeping decimals for sub-second precision); TO_TIMESTAMP returns TIMESTAMPTZ in the session time zone; AT TIME ZONE 'UTC' pins it explicitly. | date_parsing | intermediate | train |
DCR0115 | An R data frame from an API has a list-column 'tags' where each cell contains a character vector. Unnest it to one row per tag. | post_id,tags
1,c('python','data')
2,c('sql')
3,c('r','statistics','data') | R | dplyr | library(dplyr)
library(tidyr)
df <- tibble(
post_id = c(1, 2, 3),
tags = list(c("python", "data"), c("sql"), c("r", "statistics", "data"))
)
df_long <- df |> unnest(tags)
| When a column contains list objects, unnest() from tidyr expands each list element to its own row while repeating the other columns — the R equivalent of pandas explode(). | structural_issues | beginner | train |
DCR0057 | A 'sales' table has a 'revenue' column with extreme high outliers (top 1%). Identify and cap them at the 99th percentile. | sale_id | revenue
--------+---------
1 | 1500
2 | 9200000
3 | 1800
4 | 1250 | SQL | PostgreSQL | WITH percentile AS (
SELECT PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY revenue) AS p99
FROM sales
)
UPDATE sales
SET revenue = (SELECT p99 FROM percentile)
WHERE revenue > (SELECT p99 FROM percentile);
| PERCENTILE_CONT(0.99) computes a continuous (interpolated) 99th percentile; the CTE makes it available for a single scan; the UPDATE replaces outliers with the cap value in-place. | outlier_handling | advanced | train |
DCR0013 | A 'country' column has inconsistent capitalisation and whitespace: ' united states ', 'United States', 'UNITED STATES'. Normalise to Title Case stripped of whitespace. | user_id,country
1, united states
2,United States
3,UNITED STATES
4, canada | Python | pandas | import pandas as pd
df = pd.read_csv("users.csv")
df["country"] = df["country"].str.strip().str.title()
| str.strip() removes leading/trailing whitespace; str.title() capitalises the first letter of each word, giving a consistent canonical form. | string_normalization | beginner | train |
DCR0009 | A user table has exact duplicate rows from a bad ETL merge. Remove all duplicate rows, keeping the first occurrence. | user_id,email,name
1,alice@example.com,Alice
1,alice@example.com,Alice
2,bob@example.com,Bob | Python | pandas | import pandas as pd
df = pd.read_csv("users.csv")
df = df.drop_duplicates(keep="first")
| drop_duplicates() compares all columns by default; keep='first' retains the earliest occurrence and drops subsequent exact copies. | deduplication | beginner | train |
DCR0024 | A CSV has date strings in a non-standard format: '25 January 2024' and '3rd February 2024'. Parse them to datetime. | id,purchase_date
1,25 January 2024
2,3rd February 2024
3,14 March 2024 | Python | pandas | import pandas as pd
import re
def strip_ordinal(s: str) -> str:
return re.sub(r"(\d+)(st|nd|rd|th)\b", r"\1", s)
df = pd.read_csv("purchases.csv")
df["purchase_date"] = pd.to_datetime(
df["purchase_date"].map(strip_ordinal), format="%d %B %Y"
)
| Ordinal suffixes (st/nd/rd/th) confuse standard parsers; stripping them with a small regex before pd.to_datetime with an explicit format is reliable and fast. | date_parsing | intermediate | train |
DCR0090 | A DataFrame has per-group outliers: within each 'department', salaries more than 2.5 SD from the department mean should be capped at the department-level bounds. | emp_id,department,salary
1,Eng,95000
2,Eng,2000000
3,Eng,102000
4,Sales,60000
5,Sales,55000 | Python | pandas | import pandas as pd
df = pd.read_csv("employees.csv")
def cap_group(g):
m, s = g["salary"].mean(), g["salary"].std(ddof=1)
g["salary"] = g["salary"].clip(m - 2.5*s, m + 2.5*s)
return g
df = df.groupby("department", group_keys=False).apply(cap_group)
| apply(cap_group) operates on each department DataFrame independently, so department-specific means and SDs drive the caps rather than a single global statistic. | outlier_handling | advanced | train |
DCR0123 | A Polars DataFrame has a 'created_at' string column in RFC 3339 format. Parse it and extract 'date' and 'hour' as separate columns. | id,created_at
1,2024-01-15T08:30:00Z
2,2024-01-15T14:05:22Z
3,2024-01-16T01:12:45Z | Python | polars | import polars as pl
df = pl.read_csv("logs.csv")
df = df.with_columns(
pl.col("created_at").str.strptime(pl.Datetime("us", "UTC"), "%Y-%m-%dT%H:%M:%SZ")
).with_columns(
pl.col("created_at").dt.date().alias("date"),
pl.col("created_at").dt.hour().alias("hour"),
)
| Polars Datetime("us", "UTC") creates a microsecond-precision UTC-aware dtype; dt.date() and dt.hour() extract components efficiently without Python datetime conversions. | date_parsing | intermediate | train |
DCR0015 | A text column has HTML entities like '&', '<', '>' leftover from a web scrape. Unescape them to plain text. | id,description
1,Widgets & Gadgets
2,Price < $50
3,Score > 90% | Python | pandas | import pandas as pd
from html import unescape
df = pd.read_csv("items.csv")
df["description"] = df["description"].map(unescape)
| Python's built-in html.unescape() handles all standard HTML entities correctly without requiring an external library. | string_normalization | beginner | train |
DCR0083 | A transactions DataFrame has near-duplicates where the same payment was recorded twice with slightly different timestamps (within 60 seconds). Deduplicate on (user_id, amount) with a time tolerance. | tx_id,user_id,amount,ts
1,U1,50.00,2024-01-01 10:00:00
2,U1,50.00,2024-01-01 10:00:45
3,U2,30.00,2024-01-01 11:00:00 | Python | pandas | import pandas as pd
df = pd.read_csv("transactions.csv", parse_dates=["ts"])
df = df.sort_values(["user_id", "amount", "ts"])
# Flag rows within 60s of the previous same (user, amount) pair
grp = df.groupby(["user_id", "amount"])
time_diff = grp["ts"].diff().dt.total_seconds()
df = df[~((time_diff < 60) & (time_diff ... | Sorting first ensures consecutive rows in each group are chronologically ordered; diff() computes the gap in seconds; rows within 60 s of the prior same-amount same-user transaction are the duplicates. | deduplication | advanced | train |
DCR0125 | Use pandera to define a schema for a financial transactions DataFrame and validate it, catching both type errors and value-range violations in one call. | tx_id,amount,status
1,150.0,completed
2,-20.0,completed
3,75.0,unknown | Python | pandera | import pandas as pd
import pandera as pa
schema = pa.DataFrameSchema({
"tx_id": pa.Column(int, nullable=False),
"amount": pa.Column(float, pa.Check.ge(0), nullable=False),
"status": pa.Column(str, pa.Check.isin(["pending", "completed", "cancelled"])),
})
df = pd.read_csv("transactions.csv")
try:
sche... | pandera's lazy=True mode collects all violations before raising, producing a failure_cases DataFrame that shows exactly which rows and columns failed which checks. | validation | intermediate | train |
DCR0126 | Use Great Expectations to validate that a 'users' DataFrame has no nulls in 'email', all emails are unique, and 'age' is between 18 and 100. | user_id,email,age
1,alice@example.com,25
2,,17
3,alice@example.com,30 | Python | great_expectations | import great_expectations as ge
df = ge.read_csv("users.csv")
results = [
df.expect_column_values_to_not_be_null("email"),
df.expect_column_values_to_be_unique("email"),
df.expect_column_values_to_be_between("age", min_value=18, max_value=100),
]
for r in results:
if not r["success"]:
print(f... | Great Expectations wraps pandas and adds expectation methods; each returns a dict with success, result, and expectation_config; iterating over results gives a structured validation report. | validation | intermediate | train |
DCR0022 | A transactions table stores Unix epoch timestamps (seconds) as integers. Convert to UTC-aware datetime and then to 'America/New_York' local time. | tx_id,created_at
1,1700000000
2,1700086400
3,1700172800 | Python | pandas | import pandas as pd
df = pd.read_csv("transactions.csv")
df["created_at"] = (
pd.to_datetime(df["created_at"], unit="s", utc=True)
.dt.tz_convert("America/New_York")
)
| unit='s' interprets integers as seconds; utc=True makes the result tz-aware; tz_convert() then shifts to the target timezone without losing the offset info. | date_parsing | intermediate | train |
DCR0087 | A 'description' column has markdown bold markers (**text**) from a CMS import. Strip them and keep plain text. | id,description
1,**High quality** widget
2,Fast **shipping** available
3,No markdown here | Python | pandas | import pandas as pd
df = pd.read_csv("products.csv")
df["description"] = df["description"].str.replace(r"\*\*", "", regex=True)
| Escaping each asterisk in the regex pattern with double backslash matches literal ** markers; replacing with empty string strips the formatting while preserving the enclosed text. | string_normalization | beginner | train |
DCR0104 | A 'users' table has email duplicates (case-insensitive). Find all duplicate groups showing each variant. | id | email
---+-----------------------
1 | Alice@Example.com
2 | alice@example.com
3 | Bob@Example.com | SQL | PostgreSQL | SELECT
LOWER(email) AS email_canonical,
COUNT(*) AS duplicate_count,
ARRAY_AGG(email ORDER BY id) AS variants,
ARRAY_AGG(id ORDER BY id) AS ids
FROM users
GROUP BY LOWER(email)
HAVING COUNT(*) > 1;
| GROUP BY LOWER(email) groups case-insensitive variants together; ARRAY_AGG captures each distinct variant and ID for remediation; HAVING > 1 limits output to actual duplicates. | deduplication | intermediate | train |
DCR0108 | A 'events' table has overlapping time windows (start_ts, end_ts) for the same user that indicate duplicate bookings. Find rows where a user has overlapping intervals. | event_id | user_id | start_ts | end_ts
---------+---------+---------------------+-------------------
1 | U1 | 2024-01-01 10:00:00 | 2024-01-01 11:00:00
2 | U1 | 2024-01-01 10:30:00 | 2024-01-01 12:00:00 | SQL | PostgreSQL | SELECT
a.event_id AS event_a,
b.event_id AS event_b,
a.user_id,
a.start_ts, a.end_ts,
b.start_ts AS b_start, b.end_ts AS b_end
FROM events a
JOIN events b
ON a.user_id = b.user_id
AND a.event_id < b.event_id
AND a.start_ts < b.end_ts
AND a.end_ts > b.start_ts;
| Self-joining with event_id < b.event_id avoids reporting each pair twice; the overlap condition (Allen's interval algebra) detects any partial or total overlap between two intervals. | validation | advanced | train |
DCR0110 | A PostgreSQL 'metrics' table has rows with duplicate (metric_name, recorded_date) combinations where only the latest inserted row (by id) should be kept. Delete the older duplicates. | id | metric_name | recorded_date | value
---+-------------+---------------+------
1 | cpu_pct | 2024-01-01 | 45.2
2 | cpu_pct | 2024-01-01 | 46.1
3 | mem_pct | 2024-01-01 | 70.0 | SQL | PostgreSQL | WITH latest AS (
SELECT MAX(id) AS keep_id
FROM metrics
GROUP BY metric_name, recorded_date
)
DELETE FROM metrics
WHERE id NOT IN (SELECT keep_id FROM latest);
| MAX(id) selects the most recently inserted row per (metric_name, recorded_date) group; the DELETE removes everything except those rows, cleaning duplicates without needing a window function. | deduplication | intermediate | train |
DCR0052 | A 'orders' table has a 'tags' column storing comma-separated values (e.g. 'urgent,fragile,perishable'). Unnest it into a one-row-per-tag child table. | order_id | tags
---------+------------------------
1 | urgent,fragile
2 | perishable
3 | urgent,perishable,fragile | SQL | PostgreSQL | CREATE TABLE order_tags AS
SELECT
order_id,
TRIM(tag) AS tag
FROM orders,
LATERAL UNNEST(STRING_TO_ARRAY(tags, ',')) AS tag;
| STRING_TO_ARRAY splits on the delimiter; UNNEST expands the array to rows; LATERAL makes the function refer to columns from the left table; TRIM cleans up whitespace. | structural_issues | intermediate | train |
DCR0037 | A numeric 'age' column should be between 0 and 120. Replace out-of-range values with NaN and log the count of violations. | person_id,age
1,25
2,-5
3,130
4,42 | Python | pandas | import pandas as pd
import numpy as np
df = pd.read_csv("persons.csv")
out_of_range = ~df["age"].between(0, 120)
print(f"{out_of_range.sum()} out-of-range age values replaced with NaN")
df.loc[out_of_range, "age"] = np.nan
| between() creates a clean boolean mask; printing the violation count before nullifying gives auditability without a separate validation pass. | validation | beginner | train |
DCR0106 | A 'orders' table has a 'notes' column with NULL and empty-string values that both mean 'no notes'. Standardise empty strings to NULL. | order_id | notes
---------+-------
1 | Rush delivery
2 |
3 | NULL
4 | Gift wrap | SQL | PostgreSQL | UPDATE orders
SET notes = NULL
WHERE TRIM(notes) = '' OR notes IS NULL;
| Trimming before comparison catches notes that contain only whitespace; setting them to NULL makes the absence of notes semantically unambiguous and consistent for IS NULL checks. | missing_values | beginner | train |
DCR0021 | A CSV has a 'date' column with mixed formats: 'YYYY-MM-DD', 'MM/DD/YYYY', and 'DD-Mon-YYYY'. Parse all into a single datetime column. | event_id,date
1,2024-03-15
2,03/15/2024
3,15-Mar-2024 | Python | pandas | import pandas as pd
df = pd.read_csv("events.csv")
df["date"] = pd.to_datetime(df["date"], infer_datetime_format=True, dayfirst=False)
| pd.to_datetime with infer_datetime_format tries common formats automatically; for ambiguous cases the dayfirst parameter controls the MM/DD vs DD/MM interpretation. | date_parsing | beginner | train |
DCR0033 | A DataFrame imported from Excel has messy column names with spaces, special characters, and mixed case (e.g. 'First Name', 'Phone #', 'E-Mail Address'). Normalise to snake_case. | First Name,Last Name,Phone #,E-Mail Address
Alice,Smith,(555)123-4567,alice@example.com | Python | pandas | import pandas as pd
import re
def to_snake(col: str) -> str:
col = col.strip().lower()
col = re.sub(r"[^a-z0-9]+", "_", col)
return col.strip("_")
df = pd.read_csv("contacts.csv")
df.columns = [to_snake(c) for c in df.columns]
| Lowercasing first prevents CamelCase issues; the regex replaces any non-alphanumeric run with an underscore; strip('_') removes leading/trailing underscores from e.g. '#phone'. | column_renaming | beginner | train |
DCR0074 | A Polars DataFrame has null values in a 'price' column. Fill nulls with the column mean. | product_id,price
1,9.99
2,null
3,14.99
4,null | Python | polars | import polars as pl
df = pl.read_csv("products.csv")
mean_price = df["price"].mean()
df = df.with_columns(
pl.col("price").fill_null(mean_price)
)
| fill_null() in Polars takes a literal value or expression; computing the mean separately (a scalar) and passing it as a literal is the most readable approach. | missing_values | beginner | train |
DCR0117 | An R data frame has duplicate column names after cbind(). Select the first occurrence of each column name and drop the rest. | # df has columns: id, name, score, score
# After cbind of two frames | R | dplyr | library(dplyr)
# Keep only the first occurrence of each column name
df <- df[, !duplicated(names(df))]
| duplicated(names(df)) returns TRUE for the second and later occurrences of each name; negating and using it as a column index retains only the first copy. | column_renaming | beginner | train |
DCR0003 | An employee table has multiple columns that are all null for some rows — these rows represent deleted accounts and should be dropped entirely. | emp_id,name,department,salary
101,Alice,Engineering,95000
102,,,
103,Bob,Marketing,72000 | Python | pandas | import pandas as pd
df = pd.read_csv("employees.csv")
# Drop rows where every column except the primary key is null
subset = [c for c in df.columns if c != "emp_id"]
df = df.dropna(subset=subset, how="all")
| dropna with how='all' on the non-key columns removes only rows where every data field is missing, preserving rows with partial data. | missing_values | beginner | train |
DCR0029 | A JSON-like 'metadata' column contains serialised dicts (e.g. "{'color': 'red', 'size': 'M'}"). Parse it and expand into separate columns. | product_id,metadata
1,"{'color': 'red', 'size': 'M'}"
2,"{'color': 'blue', 'size': 'L'}"
3,"{'color': 'green', 'size': 'S'}" | Python | pandas | import pandas as pd
import ast
df = pd.read_csv("products.csv")
meta_df = df["metadata"].map(ast.literal_eval).apply(pd.Series)
df = pd.concat([df.drop(columns=["metadata"]), meta_df], axis=1)
| ast.literal_eval safely parses Python literal syntax without exec(); apply(pd.Series) normalises the dict into columns; concat merges back with the original DataFrame. | structural_issues | intermediate | train |
DCR0006 | A boolean flag column contains mixed representations: 'yes'/'no', 1/0, and True/False. Standardise to Python bool. | user_id,is_active
1,yes
2,0
3,True
4,no
5,1 | Python | pandas | import pandas as pd
TRUTHY = {"yes", "1", "true", "t", "y"}
df = pd.read_csv("users.csv", dtype=str)
df["is_active"] = df["is_active"].str.lower().str.strip().isin(TRUTHY)
| Casting everything to lowercase string first normalises the representations; isin(TRUTHY) maps to bool cleanly without eval() or fragile conditionals. | type_conversion | beginner | train |
DCR0120 | A Polars DataFrame has multiple string columns with leading/trailing whitespace. Strip all string columns at once. | id,name,city
1, Alice , New York
2,Bob , London
3, Carol, Paris | Python | polars | import polars as pl
df = pl.read_csv("contacts.csv")
str_cols = [c for c, d in zip(df.columns, df.dtypes) if d == pl.Utf8]
df = df.with_columns(
[pl.col(c).str.strip_chars() for c in str_cols]
)
| Detecting Utf8 columns dynamically avoids hardcoding names; a list comprehension builds strip_chars() expressions for all of them; with_columns applies them in one pass. | string_normalization | intermediate | train |
DCR0030 | A 'name' column contains first and last name concatenated (e.g. 'Alice Smith'). Split into separate 'first_name' and 'last_name' columns, handling middle names gracefully. | id,name
1,Alice Smith
2,Bob James Jones
3,Carol Davis | Python | pandas | import pandas as pd
df = pd.read_csv("people.csv")
split = df["name"].str.split(n=1, expand=True)
df["first_name"] = split[0]
df["last_name"] = split[1].fillna("")
df = df.drop(columns=["name"])
| str.split(n=1) splits on the first space only, treating everything after the first token as the last name (including middle names); fillna covers single-word names. | structural_issues | beginner | train |
DCR0088 | A CSV has date ranges in a single column like '2024-01-01 to 2024-01-31'. Split into 'start_date' and 'end_date' datetime columns. | id,date_range
1,2024-01-01 to 2024-01-31
2,2024-02-01 to 2024-02-28
3,2024-03-01 to 2024-03-31 | Python | pandas | import pandas as pd
df = pd.read_csv("periods.csv")
split = df["date_range"].str.split(r"\s+to\s+", expand=True)
df["start_date"] = pd.to_datetime(split[0])
df["end_date"] = pd.to_datetime(split[1])
df = df.drop(columns=["date_range"])
| str.split with a regex handles variable whitespace around 'to'; expand=True returns a DataFrame of two columns that are converted to datetime independently. | date_parsing | intermediate | train |
DCR0096 | A DataFrame from an API has a JSON 'metadata' column. Validate that all rows have the required keys ('source', 'version') before processing. | id,metadata
1,"{\"source\": \"api\", \"version\": 2}"
2,"{\"source\": \"manual\"}" | Python | pandas | import pandas as pd
import ast
REQUIRED_KEYS = {"source", "version"}
df = pd.read_csv("records.csv")
df["meta_parsed"] = df["metadata"].map(ast.literal_eval)
missing_keys = df["meta_parsed"].map(
lambda d: REQUIRED_KEYS - d.keys()
)
violations = df[missing_keys.map(len) > 0]
if not violations.empty:
print(f"{... | Parsing each JSON dict once with ast.literal_eval before set-difference checking avoids repeated parsing; printing the specific missing keys per record makes remediation straightforward. | validation | intermediate | train |
DCR0041 | A 'readings' table has NULL temperature values for sensor outages. Fill each NULL with the previous non-NULL value in the same sensor's time series. | sensor_id | recorded_at | temperature
----------+---------------------+------------
S01 | 2024-01-01 00:00:00 | 21.3
S01 | 2024-01-01 00:05:00 | NULL
S01 | 2024-01-01 00:10:00 | 21.8 | SQL | PostgreSQL | SELECT
sensor_id,
recorded_at,
COALESCE(
temperature,
LAST_VALUE(temperature IGNORE NULLS) OVER (
PARTITION BY sensor_id
ORDER BY recorded_at
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
) AS temperature
FROM readings;
| LAST_VALUE with IGNORE NULLS (supported in PostgreSQL 16+ / Redshift) acts as a forward-fill window function; COALESCE applies it only where the raw value is NULL. | missing_values | advanced | train |
DCR0119 | An R data frame has a free-text 'gender' column with many variants: 'M', 'Male', 'MALE', 'F', 'Female', 'FEMALE'. Recode to 'Male', 'Female', or 'Other'. | id,gender
1,M
2,Male
3,MALE
4,F
5,Female
6,FEMALE
7,Non-binary | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("respondents.csv") |>
mutate(gender = case_when(
tolower(gender) %in% c("m", "male") ~ "Male",
tolower(gender) %in% c("f", "female") ~ "Female",
TRUE ~ "Other"
))
| case_when evaluates conditions in order; tolower() normalises before matching, catching all-caps and abbreviated variants; the TRUE fallback maps unrecognised values to 'Other'. | string_normalization | beginner | train |
DCR0055 | A 'transfers' table should be self-balancing: the sum of all 'amount' values per 'batch_id' must equal zero. Identify unbalanced batches. | transfer_id | batch_id | amount
------------+----------+--------
1 | B001 | 100
2 | B001 | -100
3 | B002 | 200
4 | B002 | -150 | SQL | PostgreSQL | SELECT batch_id, SUM(amount) AS batch_total
FROM transfers
GROUP BY batch_id
HAVING SUM(amount) <> 0;
| HAVING filters aggregated groups after GROUP BY; batches that don't sum to zero are returned as violations — a simple double-entry bookkeeping integrity check. | validation | beginner | train |
DCR0080 | A time-series DataFrame indexed by date has missing dates (non-consecutive). Reindex to a complete daily date range and forward-fill values. | date,sales
2024-01-01,100
2024-01-03,120
2024-01-05,115 | Python | pandas | import pandas as pd
df = pd.read_csv("sales.csv", parse_dates=["date"], index_col="date")
full_idx = pd.date_range(df.index.min(), df.index.max(), freq="D")
df = df.reindex(full_idx).ffill()
df.index.name = "date"
| reindex on a complete DatetimeIndex inserts NaN for missing dates; ffill propagates the last known value forward, maintaining a continuous series without gaps. | missing_values | intermediate | train |
DCR0124 | A Polars DataFrame has duplicate rows. Remove duplicates using subset of key columns, keeping the row with the highest 'score'. | user_id,email,score
1,alice@example.com,85
1,alice@example.com,92
2,bob@example.com,70 | Python | polars | import polars as pl
df = pl.read_csv("users.csv")
df = (
df.sort("score", descending=True)
.unique(subset=["user_id", "email"], keep="first")
)
| Sorting descending by score before unique() with keep='first' ensures the top-scoring row is the one retained per key combination — a clean sort-then-dedup pattern. | deduplication | intermediate | train |
DCR0086 | A 'product_code' column has mixed separators: 'AB-1234', 'AB_1234', 'AB 1234'. Normalise to 'AB-1234' format. | id,product_code
1,AB-1234
2,AB_1234
3,AB 1234
4,CD-5678 | Python | pandas | import pandas as pd
df = pd.read_csv("products.csv")
df["product_code"] = df["product_code"].str.replace(r"[_ ]", "-", regex=True)
| A character-class regex [_ ] matches either underscore or space in one pass and replaces with a hyphen, standardising all three formats to the canonical form. | string_normalization | beginner | train |
DCR0101 | A PostgreSQL 'products' table has a 'specs' JSONB column. Extract the nested 'weight_kg' value from it as a new computed column in a query. | product_id | specs
-----------+------------------------------------
1 | {"weight_kg": 1.5, "color": "red"}
2 | {"weight_kg": 0.8, "color": "blue"} | SQL | PostgreSQL | SELECT
product_id,
(specs->>'weight_kg')::NUMERIC AS weight_kg
FROM products;
| ->> extracts a JSONB key as text; ::NUMERIC casts the text to a number; using ->> instead of -> avoids the extra JSON-to-text conversion step. | structural_issues | beginner | train |
DCR0050 | A 'bookings' table stores 'check_in' as TEXT in 'YYYYMMDD' format (e.g. '20240315'). Convert to proper DATE. | booking_id | check_in
-----------+---------
1 | 20240315
2 | 20240401
3 | 20241231 | SQL | PostgreSQL | ALTER TABLE bookings ADD COLUMN check_in_date DATE;
UPDATE bookings
SET check_in_date = TO_DATE(check_in, 'YYYYMMDD');
| TO_DATE with 'YYYYMMDD' format parses the compact integer-like string correctly; a new column avoids data loss before the migration is verified. | date_parsing | beginner | train |
DCR0042 | A 'logs' table stores IP addresses as TEXT. Cast them to the PostgreSQL inet type for proper range queries. | log_id | ip_address
-------+-----------
1 | 192.168.1.1
2 | 10.0.0.5
3 | invalid_ip | SQL | PostgreSQL | -- First, identify invalid IPs
SELECT log_id, ip_address
FROM logs
WHERE ip_address !~ '^(\d{1,3}\.){3}\d{1,3}$';
-- Then cast valid ones
ALTER TABLE logs ADD COLUMN ip_inet inet;
UPDATE logs
SET ip_inet = ip_address::inet
WHERE ip_address ~ '^(\d{1,3}\.){3}\d{1,3}$';
| Validating before casting prevents the UPDATE from failing on malformed rows; the regex filters to four-octet patterns before the ::inet cast. | type_conversion | intermediate | train |
DCR0018 | A salary column has obvious data-entry errors: values below $1,000 or above $1,000,000. Clip them to a valid range [20000, 500000]. | employee_id,salary
1,95000
2,150
3,72000
4,9999999 | Python | pandas | import pandas as pd
df = pd.read_csv("employees.csv")
df["salary"] = df["salary"].clip(lower=20_000, upper=500_000)
| clip() caps values at the specified bounds without removing rows, keeping the dataset size constant while constraining extreme values. | outlier_handling | beginner | train |
DCR0016 | A free-text 'job_title' column has many surface variants of the same role: 'Sr. Engineer', 'Senior Engineer', 'Senior Eng.', 'Snr Engineer'. Map all variants to a canonical form. | employee_id,job_title
1,Sr. Engineer
2,Senior Engineer
3,Senior Eng.
4,Snr Engineer
5,Junior Developer | Python | pandas | import pandas as pd
import re
TITLE_MAP = {
r"(?i)\b(sr\.?|snr|senior)\s+(eng(?:ineer)?|eng\.)": "Senior Engineer",
r"(?i)\bjunior\s+dev(?:eloper)?": "Junior Developer",
}
def normalise_title(t: str) -> str:
for pattern, canonical in TITLE_MAP.items():
if re.search(pattern, t):
return ... | A small dictionary of regex patterns to canonical strings is easy to extend and keeps business logic explicit and auditable. | string_normalization | intermediate | train |
DCR0112 | An R data frame has multiple columns with NA. Drop any column where more than 50% of values are missing. | id,a,b,c
1,1,NA,5
2,2,NA,6
3,3,NA,7
4,4,8,8 | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("data.csv")
df <- df |>
select(where(~ mean(is.na(.x)) <= 0.5))
| select(where(...)) filters columns by a predicate; mean(is.na(.x)) gives the fraction of NAs per column; columns with > 50% missing are dropped. | missing_values | intermediate | train |
DCR0109 | A 'log_entries' table has a 'level' column with inconsistent capitalisation: 'INFO', 'info', 'Info'. Add a CHECK constraint after normalising. | log_id | level | message
-------+-------+---------
1 | INFO | Started
2 | info | Running
3 | Error | Failed | SQL | PostgreSQL | -- Normalise existing data
UPDATE log_entries
SET level = UPPER(level);
-- Add constraint to enforce future entries
ALTER TABLE log_entries
ADD CONSTRAINT chk_level
CHECK (level IN ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'));
| Normalising existing data before adding the CHECK constraint prevents the ALTER TABLE from failing; UPPER() is idempotent so running it multiple times is safe. | string_normalization | intermediate | train |
DCR0081 | A DataFrame has a 'size' column with values like 'S', 'M', 'L', 'XL'. Convert to an ordered categorical for correct sorting. | id,name,size
1,Shirt,M
2,Pants,S
3,Jacket,XL
4,Hat,L | Python | pandas | import pandas as pd
SIZE_ORDER = ["S", "M", "L", "XL", "XXL"]
df = pd.read_csv("products.csv")
df["size"] = pd.Categorical(df["size"], categories=SIZE_ORDER, ordered=True)
| pd.Categorical with ordered=True and an explicit category list enables meaningful comparisons (df['size'] > 'M') and correct sort order without numeric proxies. | type_conversion | intermediate | train |
DCR0045 | A 'customers' table has duplicate rows from a failed import. Delete all but the row with the lowest ctid (internal physical row address) for each duplicate email. | id | email | name
---+-----------------+------
1 | alice@example.com | Alice
2 | alice@example.com | Alice
3 | bob@example.com | Bob | SQL | PostgreSQL | DELETE FROM customers
WHERE ctid NOT IN (
SELECT MIN(ctid)
FROM customers
GROUP BY email
);
| ctid is PostgreSQL's physical row identifier, unique within a table; MIN(ctid) per group selects the first-inserted row; deleting all others removes exact duplicates without a surrogate key. | deduplication | intermediate | train |
DCR0008 | A log file has a 'latency_ms' column stored as strings like '120ms', '3.5s', '450ms'. Parse all values to milliseconds as float. | request_id,latency_ms
1,120ms
2,3.5s
3,450ms
4,1.2s | Python | pandas | import pandas as pd
import re
def parse_latency(val: str) -> float:
m = re.fullmatch(r"([0-9.]+)(ms|s)", val.strip())
if not m:
return float("nan")
amount, unit = float(m.group(1)), m.group(2)
return amount if unit == "ms" else amount * 1000
df = pd.read_csv("logs.csv", dtype=str)
df["latency_... | A small regex parser handles both units; returning NaN for unrecognised formats keeps the column numeric and makes anomalies visible downstream. | type_conversion | intermediate | train |
DCR0129 | A DataFrame has highly skewed 'price' column with a long right tail. Apply Winsorization at the 5th and 95th percentiles. | id,price
1,10
2,5000000
3,25
4,30
5,5
6,9999999 | Python | pandas | import pandas as pd
from scipy.stats import mstats
df = pd.read_csv("products.csv")
df["price"] = mstats.winsorize(df["price"], limits=[0.05, 0.05])
| scipy.stats.mstats.winsorize sets values below the 5th percentile to the 5th percentile value and above the 95th to the 95th; it reduces outlier influence without removing rows. | outlier_handling | intermediate | train |
DCR0113 | An R data frame has a 'score' column that should be between 0 and 100. Flag and remove out-of-range rows. | student_id,score
1,85
2,110
3,72
4,-5 | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("scores.csv")
violations <- filter(df, score < 0 | score > 100)
message(sprintf("%d out-of-range score(s) removed", nrow(violations)))
df <- filter(df, between(score, 0, 100))
| between() is dplyr's inclusive range check; reporting violations before filtering provides an audit trail; message() writes to stderr so it appears in logs without polluting the return value. | outlier_handling | beginner | train |
DCR0116 | An R data frame has column names read from a messy source file with duplicates ('value', 'value.1', 'value.2'). Rename them programmatically. | id,value,value.1,value.2
1,10,20,30
2,11,21,31 | R | dplyr | library(dplyr)
library(readr)
df <- read_csv("data.csv")
names(df) <- make.unique(
gsub("\\.([0-9]+)$", "_\\1", names(df)),
sep = "_"
)
# Or give explicit meaningful names:
df <- rename(df, q1 = value, q2 = value.1, q3 = value.2)
| gsub converts the .N suffix to _N for readability; make.unique ensures uniqueness if there are still collisions; an explicit rename() is clearer when the semantic meaning is known. | column_renaming | intermediate | train |
DCR0019 | A numeric 'response_time_ms' column has extreme outliers (> 3 standard deviations from the mean). Replace outliers with NaN so downstream models aren't skewed. | request_id,response_time_ms
1,120
2,135
3,99800
4,118
5,142 | Python | pandas | import pandas as pd
import numpy as np
df = pd.read_csv("requests.csv")
col = df["response_time_ms"]
z_scores = (col - col.mean()) / col.std(ddof=1)
df.loc[z_scores.abs() > 3, "response_time_ms"] = np.nan
| Z-score comparison flags values more than 3 standard deviations away; setting them to NaN (rather than dropping rows) preserves other columns for imputation later. | outlier_handling | intermediate | train |
DCR0084 | A 'postal_code' column has US zip codes as integers (50001) and strings with leading zeros ('02134'). Normalise all to zero-padded 5-character strings. | id,postal_code
1,02134
2,50001
3,7302 | Python | pandas | import pandas as pd
df = pd.read_csv("addresses.csv", dtype={"postal_code": str})
df["postal_code"] = df["postal_code"].str.strip().str.zfill(5)
| Reading with dtype=str prevents pandas from stripping leading zeros during CSV parsing; zfill(5) pads shorter codes with leading zeros to produce a uniform 5-character string. | string_normalization | beginner | train |
DCR0102 | A PostgreSQL table stores comma-separated email addresses in a 'recipients' column. Validate that each individual email matches a basic email pattern. | id | recipients
---+--------------------------------------
1 | alice@example.com,bob@example.com
2 | carol@example.com,NOT_AN_EMAIL | SQL | PostgreSQL | SELECT
id,
recipient,
recipient ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$' AS is_valid
FROM (
SELECT id, UNNEST(STRING_TO_ARRAY(recipients, ',')) AS recipient
FROM email_list
) sub;
| STRING_TO_ARRAY + UNNEST expands the delimited list to rows; the ~ operator applies a POSIX regex per row; returning a boolean flag rather than deleting lets the application decide how to handle invalid entries. | validation | intermediate | train |
DCR0060 | A PostgreSQL text column imported from a Windows system has carriage returns (\r) embedded in strings. Remove them. | id | notes
---+-------------
1 | First line\r
2 | Second\r line
3 | Normal line | SQL | PostgreSQL | UPDATE documents
SET notes = REPLACE(notes, E'\r', '')
WHERE notes LIKE E'%\r%';
| E'\r' is PostgreSQL's escape-string syntax for carriage return (0x0D); REPLACE removes all occurrences; the WHERE limits updates to affected rows only. | encoding_issues | beginner | train |
DCR0118 | An R data frame has a 'created_at' POSIXct column stored in UTC. Convert it to 'US/Eastern' timezone. | id,created_at
1,2024-03-15 14:00:00 UTC
2,2024-03-15 18:30:00 UTC | R | dplyr | library(dplyr)
library(lubridate)
library(readr)
df <- read_csv("events.csv")
df <- df |>
mutate(created_at_est = with_tz(created_at, tzone = "US/Eastern"))
| lubridate::with_tz() converts the time zone representation without changing the instant in time (unlike force_tz which changes both); the original UTC column is preserved for auditing. | date_parsing | beginner | train |
DCR0089 | A DataFrame has a 'quarter' column like 'Q1 2024', 'Q2 2024'. Convert each to the first date of that quarter. | id,quarter
1,Q1 2024
2,Q3 2023
3,Q4 2024 | Python | pandas | import pandas as pd
QUARTER_START = {"Q1": "01-01", "Q2": "04-01", "Q3": "07-01", "Q4": "10-01"}
def quarter_to_date(q: str) -> pd.Timestamp:
qtr, yr = q.split()
return pd.Timestamp(f"{yr}-{QUARTER_START[qtr]}")
df = pd.read_csv("revenues.csv")
df["quarter_start"] = df["quarter"].map(quarter_to_date)
| A small lookup dict avoids complex date arithmetic; splitting on whitespace gives the quarter label and year separately; pd.Timestamp constructs a proper datetime. | date_parsing | intermediate | train |
DCR0027 | A text column has invisible Unicode control characters (U+0000–U+001F, U+200B zero-width space) that were silently imported. Strip them out. | id,comment
1,Great product!
2,Fast delivery
3,Would buy again | Python | pandas | import pandas as pd
import re
CONTROL_RE = re.compile(r"[\x00-\x1f\u200b]")
df = pd.read_csv("reviews.csv")
df["comment"] = df["comment"].str.replace(CONTROL_RE, "", regex=True)
| The regex matches ASCII control codes (0x00-0x1F) and the zero-width space U+200B; replacing them with an empty string removes invisible noise without affecting printable text. | encoding_issues | intermediate | train |
DCR0107 | A PostgreSQL table has a 'phone' column with international format '+1-555-123-4567'. Strip non-digit characters to get a raw digit string for comparison. | contact_id | phone
-----------+-----------------
1 | +1-555-123-4567
2 | (555) 987-6543
3 | 5551112222 | SQL | PostgreSQL | SELECT
contact_id,
phone,
REGEXP_REPLACE(phone, '[^0-9]', '', 'g') AS digits_only
FROM contacts;
| REGEXP_REPLACE with the 'g' flag removes all non-digit characters globally; the result is suitable for normalised comparison or storage alongside the original formatted value. | string_normalization | beginner | train |
DCR0010 | A contacts DataFrame has near-duplicate records where the same person was entered multiple times with slight email casing differences (e.g. 'Alice@Mail.com' vs 'alice@mail.com'). Deduplicate on normalised email. | id,name,email
1,Alice,Alice@Mail.com
2,Alice,alice@mail.com
3,Bob,bob@example.com | Python | pandas | import pandas as pd
df = pd.read_csv("contacts.csv")
df["email_norm"] = df["email"].str.lower().str.strip()
df = df.drop_duplicates(subset=["email_norm"], keep="first")
df = df.drop(columns=["email_norm"])
| Normalising to lowercase before deduplication catches case-insensitive duplicates; the temporary column is dropped after so the schema stays clean. | deduplication | beginner | train |
DCR0067 | An R data frame 'country' column has inconsistent capitalisation. Normalise to title case. | user_id,country
1,united states
2,CANADA
3,United Kingdom | R | dplyr | library(dplyr)
library(readr)
library(stringr)
df <- read_csv("users.csv") |>
mutate(country = str_to_title(str_trim(country)))
| str_trim() removes leading/trailing whitespace; str_to_title() capitalises the first letter of each word, producing consistent output regardless of input case. | string_normalization | beginner | train |
Data Cleaning Recipes
A curated synthetic dataset of 129 data-cleaning recipes spanning Python (pandas, polars, pandera, Great Expectations), SQL (PostgreSQL), and R (dplyr/tidyr). Each record pairs a real-world data-quality problem with a working code solution, a concrete dirty-data example, and a plain-English explanation.
Dataset Summary
| Split | Examples |
|---|---|
| train | 103 |
| val | 13 |
| test | 13 |
| total | 129 |
Schema
| Field | Type | Description |
|---|---|---|
id |
string | Unique record ID (e.g. DCR0001) |
problem_description |
string | Natural-language description of the data quality issue |
dirty_example |
string | Small snippet showing the problematic data |
language |
string | Python, SQL, or R |
library |
string | pandas, polars, PostgreSQL, dplyr, pandera, great_expectations |
cleaning_code |
string | Working code that fixes the issue |
explanation |
string | Plain-English explanation of why the code works |
issue_type |
string | One of 10 issue categories (see below) |
difficulty |
string | beginner, intermediate, or advanced |
split |
string | train, val, or test |
Issue Type Distribution
| Issue Type | Count |
|---|---|
| string_normalization | 18 |
| validation | 16 |
| missing_values | 15 |
| structural_issues | 15 |
| type_conversion | 14 |
| date_parsing | 14 |
| deduplication | 13 |
| outlier_handling | 9 |
| column_renaming | 9 |
| encoding_issues | 6 |
Language & Library Distribution
| Language | Library | Count |
|---|---|---|
| Python | pandas | 63 |
| SQL | PostgreSQL | 33 |
| R | dplyr/tidyr | 21 |
| Python | polars | 10 |
| Python | pandera / great_expectations | 2 |
Sample Records
Python / pandas — Type Conversion
Problem: A price column was imported as strings with currency symbols and commas (e.g. '$1,250.00'). Convert it to float.
Dirty example:
product,price
Widget,$1,250.00
Gadget,$89.99
Doohickey,$14,000.50
Solution:
import pandas as pd
df = pd.read_csv("products.csv")
df["price"] = (
df["price"]
.str.replace(r"[\$,]", "", regex=True)
.astype(float)
)
Explanation: str.replace with a character-class regex strips $ and , in one pass before astype(float) converts the clean string to a numeric type.
SQL / PostgreSQL
Problem: A 'transactions' table has negative amounts that should not exist (all transactions must be positive). Identify them and set to NULL pending review.
Dirty example:
tx_id | amount | type
------+--------+------
1 | 150.00 | credit
2 | -50.00 | debit
3 | 200.00 | credit
Solution:
-- Identify violations
SELECT tx_id, amount FROM transactions WHERE amount < 0;
-- Nullify pending review
UPDATE transactions
SET amount = NULL
WHERE amount < 0;
Explanation: Selecting before updating provides an audit log of what changed; setting to NULL (rather than deleting) preserves the row for review while making the invalid value explicit.
R / dplyr
Problem: An R transactions data frame has a 'status' column that should only contain 'pending', 'completed', or 'cancelled'. Flag invalid rows.
Dirty example:
tx_id,amount,status
1,100,completed
2,50,PENDING
3,200,failed
4,75,cancelled
Solution:
library(dplyr)
library(readr)
VALID <- c("pending", "completed", "cancelled")
df <- read_csv("transactions.csv") |>
mutate(status_norm = tolower(trimws(status)),
status_valid = status_norm %in% VALID)
# View violations
filter(df, !status_valid)
Explanation: Normalising to lowercase before the set-membership check catches case variants; a separate 'status_valid' flag preserves the original value while marking violations.
Usage
from datasets import load_dataset
ds = load_dataset("SalutefaceAAC/data-cleaning-recipes")
# Filter to beginner pandas recipes
pandas_beginner = ds["train"].filter(
lambda x: x["library"] == "pandas" and x["difficulty"] == "beginner"
)
# Get all SQL deduplication examples
sql_dedup = ds["train"].filter(
lambda x: x["language"] == "SQL" and x["issue_type"] == "deduplication"
)
Use Cases
- Fine-tuning code LLMs on data-quality problem solving
- Retrieval-augmented generation for data engineering assistants
- Benchmarking LLM ability to generate correct cleaning code from a problem description
- Training data for classifiers that detect data quality issue types
- Educational material for data engineering courses
Generation Methodology
All records were hand-authored by domain experts following a consistent template:
- Identify a real-world data-quality pattern from production data engineering experience
- Write a minimal dirty-data example that makes the problem concrete
- Implement a correct, idiomatic solution in the target language/library
- Write a concise technical explanation focusing on why the approach works
Records were deduplicated by MD5 hash on (problem_description, cleaning_code).
Limitations
- SQL recipes target PostgreSQL dialect; some syntax (e.g.
ctid,REGEXP_REPLACEflags) may not transfer to other databases. - Python recipes assume pandas ≥ 1.3, polars ≥ 0.19.
- R recipes assume tidyverse ≥ 2.0.
- The dataset focuses on tabular data cleaning; unstructured text, images, and audio are out of scope.
- Advanced difficulty examples (5 records) cover multi-table joins, window-function deduplication, and group-level outlier capping.
License
Apache 2.0 — free to use for any purpose with attribution.
Citation
@dataset{saluteface_data_cleaning_recipes_2024,
title = {Data Cleaning Recipes},
author = {SalutefaceAAC},
year = {2024},
url = {https://huggingface.co/datasets/SalutefaceAAC/data-cleaning-recipes},
license = {Apache-2.0}
}
- Downloads last month
- 35