Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Clean, Transform & Enrich Scraped Data

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Scraped data is rarely ready for analysis or use. It often contains duplicates, missing values, inconsistent formatting, and lacks context. This guide walks you through the practical steps to clean, transform, and enrich your scraped dataset, turning raw HTML or JSON into a structured, usable format. You'll learn the core techniques using Python and pandas, along with common pitfalls and how to fix them.

What You'll Need

  • Python 3.7+ installed on your machine.
  • The pandas library (pip install pandas).
  • Your scraped data in a common format like CSV, JSON, or a list of dictionaries.
  • Basic familiarity with Python and pandas DataFrames.

Step-by-Step

  1. Load the data into a pandas DataFrame. Start by reading your scraped file. If it's CSV, use pd.read_csv('scraped_data.csv'). For JSON, use pd.read_json('scraped_data.json'). If your data is a list of dictionaries, use pd.DataFrame(your_list). This gives you a tabular structure to work with.
  2. Inspect the data structure. Run df.head() to see the first few rows, df.info() to check column data types and non-null counts, and df.describe() for numeric columns. This initial look helps you spot obvious issues like entirely empty columns or unexpected data types.
  3. Handle missing values. Decide how to deal with NaN values. You can drop rows with missing critical data using df.dropna(subset=['column_name']), or fill them with a placeholder like df['column'] = df['column'].fillna('Unknown'). For numeric columns, you might fill with the mean or median: df['price'] = df['price'].fillna(df['price'].median()). The right choice depends on your use case—don't just drop everything blindly.
  4. Remove duplicates. Scraped data often contains repeated entries. Use df.drop_duplicates() to remove exact duplicate rows. If you want to consider only certain columns (e.g., a product ID), use df.drop_duplicates(subset=['product_id']).
  5. Standardize text formatting. Clean up string columns by stripping whitespace, converting to consistent case, and fixing common issues. For example:
    df['name'] = df['name'].str.strip()
    df['category'] = df['category'].str.lower()
    Use .str.replace() to remove unwanted characters like extra spaces or HTML entities (e.g., &).
  6. Convert data types. Ensure each column has the correct type. Use pd.to_numeric() for numbers, pd.to_datetime() for dates. For example:
    df['price'] = pd.to_numeric(df['price'], errors='coerce')
    df['date'] = pd.to_datetime(df['date'])
    The errors='coerce' parameter turns invalid values into NaN, which you can then handle.
  7. Parse and split columns. If a column contains combined information, split it into separate columns. For instance, if you have a 'location' column like "New York, NY", split it:
    df[['city', 'state']] = df['location'].str.split(',', expand=True)
    Similarly, extract parts of strings using .str.extract() with regex.
  8. Transform values. Create new columns based on existing ones. For example, calculate a price per unit or a rating category:
    df['price_per_kg'] = df['price'] / df['weight_kg']
    df['rating_category'] = pd.cut(df['rating'], bins=[0, 3, 4, 5], labels=['Low', 'Medium', 'High'])
  9. Enrich with external data. Add context from other sources. Common enrichments include:
    • Geocoding: Convert addresses to coordinates using a geocoding library.
    • Category mapping: Map product categories to a standardized taxonomy.
    • Sentiment analysis: Add sentiment scores to review text.
    • Currency conversion: Convert prices to a common currency using current exchange rates.
    For example, to add a country from a country code:
    country_map = {'US': 'United States', 'GB': 'United Kingdom'}
    df['country_name'] = df['country_code'].map(country_map)
  10. Validate the cleaned data. After all steps, run checks to ensure the data is consistent. For example, verify that numeric columns have no negative values where they shouldn't, that date ranges are sensible, and that no unexpected NaNs remain in critical columns. Use df.isnull().sum() to see missing counts.
  11. Export the final dataset. Save your cleaned and enriched data to a new file. Use df.to_csv('cleaned_data.csv', index=False) or df.to_json('cleaned_data.json', orient='records'). Always use index=False to avoid writing an extra index column.

Common Mistakes

  • Ignoring data types until the end. If you try to perform numeric operations on strings, you'll get errors or incorrect results. Convert types early.
  • Dropping rows with missing values too aggressively. This can remove valuable data. Always consider whether you can fill or impute instead.
  • Not checking for duplicates after transformations. Splitting or combining columns can create new duplicates. Re-run drop_duplicates() after major changes.
  • Applying string operations to non-string columns. This will throw an error. Ensure the column is of type object or string before using .str.
  • Forgetting to reset the index. After dropping rows, the index may have gaps. Use df.reset_index(drop=True) to fix it.

Tips

  • Keep a copy of the raw data. Always save the original scraped data before cleaning. You may need to go back if you make a mistake or want to try a different cleaning approach.
  • Document your cleaning steps. Write comments in your code or keep a log of what transformations you applied. This is crucial for reproducibility and debugging.
  • Use vectorized operations. Avoid loops over DataFrame rows. Use pandas' built-in methods like .str, .apply(), and .map() for speed and clarity.
  • Test on a sample first. Before running your cleaning pipeline on the entire dataset, test it on a small sample (e.g., df.sample(100)) to catch errors quickly.
  • Automate the pipeline. Once you have a working cleaning script, turn it into a reusable function or module so you can apply it to future scrapes.

Troubleshooting

  • Data won't load into pandas. If you get a parsing error, check the file format. For CSV, try specifying a different delimiter (sep=';'). For JSON, ensure it's valid JSON (use json.load() first).
  • Column has mixed types (e.g., numbers and text). Use pd.to_numeric(..., errors='coerce') to convert to numeric, turning invalid entries into NaN. Then handle those NaNs.
  • String operations fail with 'AttributeError: 'float' object has no attribute 'str''. This means the column has NaN values. Fill them first with fillna('') or use df['col'].astype(str).str.strip().
  • Duplicates not being removed. Check if the rows are truly identical. Sometimes hidden whitespace or different casing prevents detection. Standardize text first, then drop duplicates.
  • Date parsing fails. Use pd.to_datetime(df['date'], format='%d/%m/%Y') to specify the exact format if the default doesn't work. If you have mixed formats, try errors='coerce' and then investigate the NaNs.
  • Memory issues with large datasets. If your dataset is huge, read it in chunks using pd.read_csv(..., chunksize=10000) and process each chunk, or use dtype to specify column types to reduce memory usage.

Frequently Asked Questions

What is the difference between cleaning and transforming data?

Cleaning focuses on fixing errors, removing duplicates, and handling missing values. Transforming changes the structure or format, such as splitting columns, converting types, or creating new derived columns.

How do I handle missing values in a categorical column?

You can fill them with the mode (most frequent value), a placeholder like 'Unknown', or create a separate 'missing' category. The best choice depends on what the column represents and how you'll use it.

Should I always remove duplicates?

Not always. Sometimes duplicates are legitimate (e.g., multiple reviews for the same product). Only remove duplicates when you're sure they represent the same entity and shouldn't be counted multiple times.

What is data enrichment exactly?

Data enrichment is adding new information to your existing dataset from external sources. Examples include adding geolocation from addresses, company information from a business registry, or sentiment scores from text analysis.

Can I do this without pandas?

Yes, you can use plain Python with lists and dictionaries, but it's much more tedious and error-prone. Pandas provides efficient, vectorized operations that make cleaning and transforming data much easier and faster.

How often should I clean scraped data?

Every time you scrape. Data from the web is messy and changes over time. Always run a cleaning pipeline before using the data for analysis or feeding it into a model.