ECON 290 · Economic Data and Computing
Cleaning and Merging Data
Raw data is messy. Learn to find and fix common problems, then join two tables safely on a shared key.
Key takeaways
- Raw data almost always has duplicates, stray text, odd codes for "missing" and inconsistent spellings, so inspect before you analyze.
- Never edit the original file. Work on a copy, and keep a written list of every change you make.
- A merge joins two tables on a shared key, such as a state code, and the key must be clean and unique on at least one side.
- Check row counts before and after every merge, because a bad join can silently drop rows or multiply them.
- Missing values need a decision, not a reflex: drop them, fill them, or flag them, and say which you chose.
Picture Dana, a student who wants to answer a simple question: do states with higher unemployment have lower incomes? She downloads one file of unemployment rates and another of average incomes. She expects to drop them side by side and draw a chart by lunch.
Then she opens the first file. One state is spelled "Calif." in one place and "California" in another. Three rows are exact copies of each other. A row at the bottom says "Source: see notes." Unemployment is written as 4.1 in some rows and "4.1%" in others, and one cell just says "n/a".
Welcome to real data. Economists often say that most of an analysis is not the clever part. It is getting the numbers into a shape where the clever part can even begin. This lesson covers that work: cleaning a table, and then merging two tables into one.
Look before you touch
The first step in cleaning is not fixing anything. It is looking. Open the file and ask a few plain questions.
- How many rows and columns are there? Does that match what the source says?
- What does one row mean? One state? One state in one year? One person?
- Which columns should be numbers, and are they stored as numbers or as text?
- What do the smallest and largest values look like? Are any impossible?
That second question matters most. The thing a row stands for is called the unit of observation. Dana's unemployment file should have one row per state. If she finds 53 rows, she knows something is off, because the country has 50 states. Maybe there is a row for the District of Columbia, one for Puerto Rico and one for a national total. Those are real rows, but they are not the same kind of thing.
Think of this as walking through a room before you rearrange the furniture. You are not fixing yet. You are noticing.
The usual suspects
Messy data tends to be messy in the same few ways. Learn the list and you will spot most problems quickly.
Duplicates. The same row appears more than once, often because two downloads were stacked together. If you count duplicates as separate states, you will count their unemployment twice.
Stray rows. Footnotes, source lines, blank rows and "Total" rows often sit inside the data. A total row is dangerous. If you average the column, the total gets averaged in as if it were one more state.
Text pretending to be numbers. A cell holding "4.1%" or "$52,300" or "1,204" is text to a computer, not a number. You cannot add it until you strip the symbols and the commas.
Strange codes for missing. Different sources mark a missing value as blank, "n/a", "NA", "-", "." or even -999. That last one is the worst. If you forget it means "missing", a value of -999 will drag your average far below zero.
Inconsistent labels. "Calif.", "CA" and "California" are one state written three ways. A computer sees three different strings.
Wrong units. One file might report income in dollars and another in thousands of dollars. Nothing looks broken until you notice that one state seems to earn a thousand times more than the rest.
Dana's file starts with 60 rows. Removing the junk leaves 50, one per state. Counting at each step proves nothing was lost by accident. Example with made-up numbers.
A cleaning routine you can repeat
Here is a routine that works for almost any table. It also keeps you honest.
The first step is the one people skip. Always keep the original. If you overwrite it and later find you cleaned something wrongly, there is no way back. The lesson on reproducible work shows how to build this habit into your files.
The last step also deserves a word. A change log can be a plain list: "Removed 3 duplicate rows. Deleted 2 footnote rows. Removed 5 rows that were totals. Converted unemployment from text to numbers." Six months from now, that list is the difference between a result you can defend and a result you have to redo.
What to do about missing values
Dana's income file has two states with "n/a" for income. She has a choice, and there is no single right answer. There are three common ones.
- Drop the rows. Simple and honest, but you lose those states. If the missing states are unusual, your answer may be skewed.
- Fill them in. You might use the average of the other states, or last year's value. This keeps the row but invents a number, so you should say so.
- Keep them and flag them. Leave the cell empty, add a column that says "missing", and let the analysis skip them where needed.
The danger to avoid is silent filling with zero. A zero income is a real claim, and it is almost always false. Missing and zero are different ideas, and mixing them up is one of the most common errors in beginner work.
A good rule: ask why the value is missing. If a state forgot to report, dropping it is probably fine. If only the poorest places fail to report, then dropping them hides the very thing you are studying.
Merging: joining two tables on a key
Now Dana has two clean tables. One has unemployment by state. The other has average income by state. She wants one table with both columns. This is a merge (some programs call it a join): you match rows from two tables using a shared column, called a key.
The key must identify the same thing in both tables. A good key is something short and standard, like a two-letter state code. A poor key is a free-text name, because "New York" and "New York State" will never match.
Here are the two tables in miniature.
Unemployment Income
State Rate (%) State Income ($)
OH 4.0 OH 60000
TX 4.5 TX 64000
VT 2.5 NH 72000 Look closely. Ohio and Texas appear in both. Vermont appears only on the left. New Hampshire appears only on the right. What should the merged table contain? That depends on the type of merge.
For her chart, Dana needs states that have both numbers, so an inner join fits. But she should not choose in silence. If she used a left join instead, Vermont would appear with a blank income, and a careless average could treat that blank as a zero.
A worked example, with the arithmetic
Dana merges her two clean tables. Suppose each has exactly 50 states, but the income table spells two states differently ("Penn." and "N. Dakota"). Here is what happens.
Rows in unemployment table: 50
Rows in income table: 50
Keys that match exactly: 48
Rows after an inner join: 48
Rows lost without warning: 50 - 48 = 2 The merge ran with no error message. Yet two states vanished, and her final chart would quietly show 48 points. She only knows because she compared the counts. After fixing the two labels (or better, switching to two-letter codes for the key), all 50 match.
Now suppose the unemployment table lists each state four times, once per quarter, and the income table has one row per state. Joining them is a many-to-one merge: each of the 200 unemployment rows matches one income row. The result has 200 rows, and each state's income is repeated four times. That is correct and expected.
The trouble comes when the key is not unique on either side. Suppose the income table accidentally lists Ohio twice. Each Ohio row in the unemployment table now matches two income rows, and the result grows.
Ohio rows in unemployment table: 4
Ohio rows in income table: 2 (a duplicate)
Ohio rows after the join: 4 × 2 = 8 Four rows have become eight, with no warning. Any sum or average that includes Ohio is now wrong. This is why you check that the key is unique where it is supposed to be unique, and why you recount rows after every merge.
If the final count differs from the expected count, stop and find out why before drawing any chart. Example with made-up numbers.
The mistakes that cost the most
Merging on names instead of codes. Free-text names break easily. Use a standard code when one exists: a state postal code, a country code or an official series identifier. The agencies in the lesson on national statistics agencies publish such codes for exactly this reason.
Trusting the merge because it ran. A computer will happily join the wrong rows. Always compare counts, and look at a few merged rows by eye.
Cleaning in a way that cannot be repeated. If you fix a cell by hand in the middle of a spreadsheet and tell no one, nobody can reproduce your result, including you. Prefer steps you can write down and run again. Spreadsheet formulas and the code in the next lesson both make this easier.
Forgetting units and time. Joining 2024 incomes to 2026 unemployment gives a tidy table that answers the wrong question. Check that the dates and units on both sides really line up.
Fixing outliers by deleting them. A state with a very high value may be a typo, or it may be true. Check the source before you remove it, and write down what you did.
Words to know
Unit of observation the thing that one row of a table describes, such as one state in one year.
Duplicate a row that repeats another row, so the same fact is counted more than once.
Missing value a cell where the number is unknown, which is not the same thing as zero.
Key a column used to match rows in two tables, such as a state code.
Merge (join) combining two tables into one by matching rows on a key.
Inner join a merge that keeps only the keys present in both tables.
Many-to-one merge a merge in which several rows of one table match a single row of the other.
Check yourself
- What is the unit of observation in a table with one row per state per year, and how many rows should it have for 50 states over 3 years?
- Why is a cell that says "4.1%" a problem for a computer, and what must you do to it before averaging?
- A file uses -999 to mean missing. Five states have it, and the other 45 average 5. If you forget the code and include the five, would the average rise or fall, and by roughly how much (give the new average)?
- Table A has keys OH, TX, VT. Table B has keys OH, TX, NH. How many rows does an inner join give, and how many does an outer join give?
- An unemployment table has 4 rows for Ohio. An income table accidentally has 3 rows for Ohio. How many Ohio rows does the merge produce, and why is that a warning sign?
- Explain why checking row counts after a merge is better than trusting that no error message appeared.
Show the answers
- One state in one year; 50 × 3 = 150 rows.
- It is text, not a number, so it cannot be added; strip the % sign and convert the cell to a number first.
- It would fall. Total = 45 × 5 + 5 × (-999) = 225 - 4995 = -4770; divide by 50 to get -95.4, a nonsense average.
- Inner join gives 2 rows (OH, TX); outer join gives 4 rows (OH, TX, VT, NH).
- 4 × 3 = 12 rows, up from 4; the key was not unique on one side, so rows multiplied and any sum or average for Ohio is now wrong.
- A merge can finish with no error while silently dropping unmatched rows or multiplying duplicated ones; only a count comparison shows that.