Spaces:
Runtime error
Runtime error
File size: 10,499 Bytes
4088a7c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | """Generate messy raw Excel files that simulate real-world client data exports.
Reads clean synthetic CSVs and introduces controlled data quality issues:
- Renamed/inconsistent column names
- Mixed date formats
- Missing values, duplicates, outliers
- Inconsistent casing and typos
"""
import pandas as pd
import numpy as np
import os
np.random.seed(99)
BASE_DIR = os.path.dirname(__file__)
SYNTHETIC_DIR = os.path.join(BASE_DIR, 'data', 'synthetic')
RAW_DIR = os.path.join(BASE_DIR, 'data', 'raw')
os.makedirs(RAW_DIR, exist_ok=True)
def mess_dates(series, formats=None, pct=1.0):
"""Convert a date column to mixed string formats."""
if formats is None:
formats = ['%m/%d/%Y', '%d-%b-%Y', '%Y/%m/%d']
result = []
for val in series:
try:
dt = pd.to_datetime(val)
if np.random.random() < pct:
fmt = np.random.choice(formats)
result.append(dt.strftime(fmt))
else:
result.append(dt.strftime('%Y-%m-%d'))
except Exception:
result.append(val)
return result
def add_duplicates(df, pct=0.03):
"""Add duplicate rows."""
n_dupes = int(len(df) * pct)
if n_dupes > 0:
dupe_idx = np.random.choice(df.index, n_dupes, replace=True)
dupes = df.loc[dupe_idx].copy()
df = pd.concat([df, dupes], ignore_index=True)
return df
def add_nulls(df, column, pct=0.08):
"""Set random values to NaN."""
mask = np.random.random(len(df)) < pct
df.loc[mask, column] = np.nan
return df
def generate_raw_media():
"""Media data with renamed columns, mixed dates, casing issues, outliers."""
df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'media_data.csv'))
# Rename columns to realistic messy names
df = df.rename(columns={
'channel': 'Media Channel',
'sub_channel': 'Sub Channel',
'spend': 'Spend_USD',
'impressions': 'Imp',
'brand': 'Brand Name',
'campaign_name': 'Campaign',
'campaign_objective': 'Objective',
'ad_format': 'Format',
'media_type': 'Type',
})
# Mix date formats
df['date'] = mess_dates(df['date'])
# Inconsistent channel casing
casing_variants = {
'TV': ['tv', 'TV ', 'Tv', 'TV', 'tv '],
'Radio': ['radio', 'RADIO', 'Radio', 'Radio '],
'Print': ['print', 'PRINT', 'Print', 'Print '],
}
for std, variants in casing_variants.items():
mask = df['Media Channel'] == std
df.loc[mask, 'Media Channel'] = np.random.choice(variants, mask.sum())
# Missing values
df = add_nulls(df, 'clicks', 0.08)
df = add_nulls(df, 'region', 0.05)
df = add_nulls(df, 'leads', 0.06)
# Outliers: 2% of spend values multiplied by 10x (fat-finger errors)
outlier_mask = np.random.random(len(df)) < 0.02
df.loc[outlier_mask, 'Spend_USD'] = df.loc[outlier_mask, 'Spend_USD'] * 10
# Add duplicates
df = add_duplicates(df, 0.03)
# Shuffle rows
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
df.to_excel(os.path.join(RAW_DIR, 'Media_Spend_Report_2024-25.xlsx'), index=False)
print(f"Raw media: {len(df)} rows -> Media_Spend_Report_2024-25.xlsx")
def generate_raw_sales():
"""Sales data with renamed columns, format issues, negative revenues."""
df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'sales_data.csv'))
# Rename columns
df = df.rename(columns={
'product': 'Product Name',
'revenue': 'Sales_Revenue',
'price': 'Unit Price',
'units_sold': 'Units',
})
# Mix date formats - some DD/MM/YYYY
dates_mixed = []
for val in df['date']:
dt = pd.to_datetime(val)
r = np.random.random()
if r < 0.4:
dates_mixed.append(dt.strftime('%d/%m/%Y'))
elif r < 0.7:
dates_mixed.append(dt.strftime('%m-%d-%Y'))
else:
dates_mixed.append(dt.strftime('%Y-%m-%d'))
df['date'] = dates_mixed
# Missing values
df = add_nulls(df, 'new_customers', 0.06)
df = add_nulls(df, 'Unit Price', 0.03)
# Outliers: 1% negative revenues (returns mixed in)
neg_mask = np.random.random(len(df)) < 0.01
df.loc[neg_mask, 'Sales_Revenue'] = -abs(df.loc[neg_mask, 'Sales_Revenue']) * np.random.uniform(0.1, 0.3, neg_mask.sum())
# Add a junk column (from prior Excel export)
df.insert(0, 'Unnamed: 0', range(len(df)))
# Add duplicates
df = add_duplicates(df, 0.02)
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
df.to_excel(os.path.join(RAW_DIR, 'Sales_Extract_All_Regions.xlsx'), index=False)
print(f"Raw sales: {len(df)} rows -> Sales_Extract_All_Regions.xlsx")
def generate_raw_consumer_promo():
"""Consumer promo with renamed cols, inconsistent promo types, mixed dates."""
df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'consumer_promo_data.csv'))
# Rename columns
df = df.rename(columns={
'promo_id': 'Promo ID',
'promo_name': 'Promo Name',
'promo_type': 'Type',
'promo_mechanic': 'Mechanic',
'promo_spend': 'Spend',
'promo_depth': 'Depth_%',
'start_date': 'Start',
'end_date': 'End',
'units_redeemed': 'Redeemed',
'total_units_distributed': 'Distributed',
'brand': 'Brand',
})
# Mix date formats for start/end
df['Start'] = mess_dates(df['Start'], ['%Y-%m-%d', '%b %d, %Y', '%m/%d/%Y'])
df['End'] = mess_dates(df['End'], ['%Y-%m-%d', '%b %d, %Y', '%m/%d/%Y'])
df['date'] = mess_dates(df['date'], ['%Y-%m-%d', '%d-%b-%Y'])
# Inconsistent promo type casing
type_variants = {
'Coupon': ['coupon', 'COUPON', 'Coupon', 'coupon '],
'Discount %': ['discount %', 'DISCOUNT %', 'Discount%', 'Discount %'],
'BOGO': ['BOGO', 'bogo', 'Bogo', 'Buy One Get One'],
'Cashback': ['cashback', 'CASHBACK', 'Cash Back', 'Cashback'],
'Free Sample': ['free sample', 'FREE SAMPLE', 'Free sample', 'FreeSample'],
'Bundle Deal': ['bundle deal', 'BUNDLE DEAL', 'Bundle', 'Bundle Deal'],
}
for std, variants in type_variants.items():
mask = df['Type'] == std
if mask.sum() > 0:
df.loc[mask, 'Type'] = np.random.choice(variants, mask.sum())
# Missing values
df = add_nulls(df, 'Redeemed', 0.10)
df = add_nulls(df, 'Depth_%', 0.07)
# Outliers: 3% extreme spend values
outlier_mask = np.random.random(len(df)) < 0.03
df.loc[outlier_mask, 'Spend'] = df.loc[outlier_mask, 'Spend'] * np.random.uniform(5, 15, outlier_mask.sum())
# Add duplicates
df = add_duplicates(df, 0.04)
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
df.to_excel(os.path.join(RAW_DIR, 'Consumer_Promotions_Master.xlsx'), index=False)
print(f"Raw consumer promo: {len(df)} rows -> Consumer_Promotions_Master.xlsx")
def generate_raw_trade_promo():
"""Trade promo with renamed cols, compliance typos, spend outliers."""
df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'trade_promo_data.csv'))
# Rename columns
df = df.rename(columns={
'event_id': 'Event ID',
'promo_type': 'Promo Type',
'retailer': 'Retailer Name',
'planned_spend': 'Plan_Spend',
'actual_spend': 'Act_Spend',
'baseline_volume': 'Base_Vol',
'actual_volume': 'Act_Vol',
'compliance_status': 'Compliance',
'start_date': 'Start Date',
'end_date': 'End Date',
})
# Mix some dates to DD-MMM-YY
date_mask = np.random.random(len(df)) < 0.05
for idx in df[date_mask].index:
try:
dt = pd.to_datetime(df.at[idx, 'date'])
df.at[idx, 'date'] = dt.strftime('%d-%b-%y')
except Exception:
pass
# Compliance status typos
compliance_typos = {
'Compliant': ['Compliant', 'compliant', 'Complient', 'COMPLIANT'],
'Partially Compliant': ['Partial', 'partially compliant', 'Partially Compliant', 'Part. Compliant'],
'Non-compliant': ['Non-compliant', 'non-compliant', 'NonCompliant', 'NC'],
}
for std, variants in compliance_typos.items():
mask = df['Compliance'] == std
if mask.sum() > 0:
df.loc[mask, 'Compliance'] = np.random.choice(variants, mask.sum())
# Missing values
df = add_nulls(df, 'Base_Vol', 0.12)
df = add_nulls(df, 'Compliance', 0.05)
# Outliers: some actual_spend values are 100x (units error)
outlier_mask = np.random.random(len(df)) < 0.02
df.loc[outlier_mask, 'Act_Spend'] = df.loc[outlier_mask, 'Act_Spend'] * 100
# Add duplicates
df = add_duplicates(df, 0.02)
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
df.to_excel(os.path.join(RAW_DIR, 'Trade_Promo_Events_Log.xlsx'), index=False)
print(f"Raw trade promo: {len(df)} rows -> Trade_Promo_Events_Log.xlsx")
def generate_raw_external():
"""External factors with renamed cols, Yes/No strings, sensor errors."""
df = pd.read_csv(os.path.join(SYNTHETIC_DIR, 'external_factors_data.csv'))
# Rename columns
df = df.rename(columns={
'temperature': 'temp_f',
'precipitation': 'rain_inches',
'holiday_flag': 'is_holiday',
'economic_index': 'econ_idx',
'competitor_price_index': 'comp_price_idx',
})
# Convert boolean holiday_flag to Yes/No strings
df['is_holiday'] = df['is_holiday'].map({True: 'Yes', False: 'No', 'True': 'Yes', 'False': 'No'})
# Convert event_flag similarly
df['event_flag'] = df['event_flag'].map({True: 'Y', False: 'N', 'True': 'Y', 'False': 'N'})
# Missing values
df = add_nulls(df, 'temp_f', 0.03)
df = add_nulls(df, 'econ_idx', 0.02)
# Sensor errors: some temperature values as -999
sensor_mask = np.random.random(len(df)) < 0.01
df.loc[sensor_mask, 'temp_f'] = -999.0
# Add duplicates
df = add_duplicates(df, 0.01)
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
df.to_excel(os.path.join(RAW_DIR, 'Weather_Economic_Data.xlsx'), index=False)
print(f"Raw external factors: {len(df)} rows -> Weather_Economic_Data.xlsx")
if __name__ == '__main__':
print("Generating messy raw Excel files...")
print("=" * 50)
generate_raw_media()
generate_raw_sales()
generate_raw_consumer_promo()
generate_raw_trade_promo()
generate_raw_external()
print("=" * 50)
print(f"All raw files generated in {RAW_DIR}")
|