Lesson

Merging Tables and Repeated Rows in pandas

Add columns from a second table, and check the rows that repeat, on real exoplanet discoveries and real car models: a lookup table built with pd.DataFrame, merge with on and how, a check of the number of rows, a key with no match, a repeated key and validate, how=outer, merge next to the JOIN of SQL, and repeated rows with duplicated, drop_duplicates, subset and keep.

Last updated:


In this lesson we learn to add columns from a second table with merge:
a lookup table, the key, how, a check of the number of rows, a key with no match and a repeated key; and to find rows that repeat with duplicated and drop_duplicates.

Planets seen directly

The planetarium exhibit of New columns and groups in pandas has a panel on planets seen directly, as a point of light of their own in an image, and planets found indirectly, from their effect on the light or the motion of a star.
The panel asks how many of each kind were found in each decade.
The table exoplanets.csv holds the method of each planet, but not whether the method sees the planet.

The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other.
The first run of the page loads pandas, so it can take a moment.

import pandas as pd

planets = pd.read_csv('exoplanets.csv')
cars = pd.read_csv('auto-mpg.csv')
print(planets.shape, cars.shape)
(1035, 6) (398, 9)

Information that is in another table

Whether a method sees the planet directly is a fact about the method, not about the planet.
Such a fact is kept once for each method, in a lookup table, as weather_types keeps the name of each kind of weather in the weather practice of SQL.

We wrote the lookup table below ourselves, for the four methods with the most rows in the table.
Imaging records the planet as a point of light of its own; radial velocity measures the motion of the star, a transit the dimming of the star, and microlensing the brightening of a more distant star.
pd.DataFrame builds a table from a dictionary whose keys are the names of the columns and whose values are the lists of their values:

seen = pd.DataFrame({
    'method': ['Radial Velocity', 'Transit', 'Imaging',
               'Microlensing'],
    'seen': ['indirect', 'indirect', 'direct', 'indirect'],
})
print(seen)
            method      seen
0  Radial Velocity  indirect
1          Transit  indirect
2          Imaging    direct
3     Microlensing  indirect

Adding columns with merge

The method merge of a table adds to each of its rows the columns of the row of another table that has the same value of a key, the column named by on.
This is a merge, the JOIN of SQL. The argument how='left' keeps every row of the table on the left, planets, also a row whose key has no match in seen.

Predict. How many rows will planets.merge(seen, on='method', how='left') have?

Show a hint

Ask how many rows of seen one planet can match.

Show a solution

1,035, as planets: each method is in at most one row of seen, so each row gets at most one match, and a row with no match is kept.

We count the rows before and after the merge, every time: the count is the check that the merge did what we meant.

merged = planets.merge(seen, on='method', how='left')
print(len(planets), len(merged))
print(merged[['method', 'year', 'seen']].head(3))
print(merged['seen'].isna().sum())
1035 1035
            method  year      seen
0  Radial Velocity  2006  indirect
1  Radial Velocity  2008  indirect
2  Radial Velocity  2011  indirect
24

Each row got the column seen of its method. The 24 rows whose method is not in seen are kept, with NaN in that column.
The method isna returns True for each missing value, and sum counts them.

A key with no match

With how='inner', the default of merge, only the rows whose key has a match are kept, as in the INNER JOIN of SQL:

inner = planets.merge(seen, on='method', how='inner')
print(len(inner))
no_match = merged[merged['seen'].isna()]
print(no_match['method'].value_counts())
1011
method
Eclipse Timing Variations        9
Pulsar Timing                    5
Transit Timing Variations        4
Orbital Brightness Modulation    3
Astrometry                       2
Pulsation Timing Variations      1
Name: count, dtype: int64

The inner merge dropped 24 rows of six methods without any message; only the count, 1,011 against 1,035, shows it.
The same happens when a key is spelled differently in the two tables:
'Radial velocity' with a small v matches none of the 553 rows of 'Radial Velocity'.

The answer for the panel

The column decade of the merged table, computed as in New columns and groups in pandas, and a pivot table, as in Groups by two columns and pivot tables in pandas, count the rows of each decade by the way they were seen:

merged['decade'] = merged['year'] // 10 * 10
print(merged.pivot_table(
    index='decade', columns='seen', aggfunc='size',
    fill_value=0,
))
seen    direct  indirect
decade                  
1980         0         1
1990         0        28
2000        20       381
2010        18       563

The table counts 1,011 rows: the 24 rows whose seen is empty are in no column, because a NaN is not a value of a column.
The six methods missing from seen all measure the star (the timing of its signals, its brightness or its position), so the panel adds them to seen as indirect and their 24 rows go to the column indirect.
Then in the 2000s, 20 of the 406 rows are planets seen directly (4.9%), and in 2010 to 2014, 18 of 597 (3.0%).

Practice

Your turn. The lookup table direct below holds one method, imaging.
Merge planets with direct so that every row of planets is kept, and print the number of rows whose seen is missing.

direct = pd.DataFrame(
    {'method': ['Imaging'], 'seen': ['direct']},
)
# your code here
Show a hint

The argument how decides what happens to a row whose key has no match.

Show a solution
direct = pd.DataFrame(
    {'method': ['Imaging'], 'seen': ['direct']},
)
kept = planets.merge(direct, on='method', how='left')
print(kept['seen'].isna().sum())
997

The 38 rows of imaging have a value; the other 997 rows are kept with NaN.

Show a common mistake and why it happens
direct = pd.DataFrame(
    {'method': ['Imaging'], 'seen': ['direct']},
)
kept = planets.merge(direct, on='method')
print(kept['seen'].isna().sum())

Without how, merge makes an inner merge, its default: it keeps only the 38 rows of imaging, so no seen is missing and the count is 0.

A repeated key multiplies rows

In seen each key appears once, so a merge keeps the number of rows of planets.
Suppose that the row of Transit was written twice, for example by two people who each added it:

seen_twice = pd.DataFrame({
    'method': ['Radial Velocity', 'Transit', 'Imaging',
               'Microlensing', 'Transit'],
    'seen': ['indirect', 'indirect', 'direct', 'indirect',
             'indirect'],
})

Predict. How many rows will planets.merge(seen_twice, on='method', how='left') have?

Show a hint

Count the rows of seen_twice that one row of a transit matches.

Show a solution

Each of the 397 rows of transits matches two rows and appears twice, so the result has 1,035 + 397 = 1,432 rows:

doubled = planets.merge(seen_twice, on='method', how='left')
print(len(doubled))
print((doubled['method'] == 'Transit').sum())
1432
794

Every count of transits in doubled is now twice the real one, and no error says so.
The argument validate='many_to_one' states that many rows on the left match at most one row on the right, and stops the merge with an error when a key repeats on the right:

planets.merge(
    seen_twice, on='method', how='left', validate='many_to_one',
)
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge

A key repeats in planets too, 553 times for radial velocity, and that is how it should be:
each planet is a row, and many planets share a method. The table whose keys must be unique is the lookup table.

Practice

Your turn. The lookup table notes below was put together from two lists written by hand.
Before merging it with planets, print with value_counts how many rows each method has in notes.

notes = pd.DataFrame({
    'method': ['Imaging', 'Transit', 'Imaging'],
    'seen': ['direct', 'indirect', 'direct'],
    'added_by': ['list 1', 'list 1', 'list 2'],
})
# your code here
Show a hint

The keys are the values of one column of notes.

Show a solution
notes = pd.DataFrame({
    'method': ['Imaging', 'Transit', 'Imaging'],
    'seen': ['direct', 'indirect', 'direct'],
    'added_by': ['list 1', 'list 1', 'list 2'],
})
print(notes['method'].value_counts())
method
Imaging    2
Transit    1
Name: count, dtype: int64

Imaging has two rows, so a merge would show each row of imaging twice.

Show a common mistake and why it happens
notes = pd.DataFrame({
    'method': ['Imaging', 'Transit', 'Imaging'],
    'seen': ['direct', 'indirect', 'direct'],
    'added_by': ['list 1', 'list 1', 'list 2'],
})
print(notes.value_counts())

value_counts on the whole table counts the rows that are equal in every column.
The two rows of Imaging differ in added_by, so each is counted once and the repeated key is not seen.

Rows of both tables: how='outer'

With how='outer' a merge keeps the rows of both tables, also a row of the lookup table whose key is in no row on the left.
Disk Kinematics, a discovery method first used after 2014, is in no row of planets:

later = pd.DataFrame({
    'method': ['Imaging', 'Disk Kinematics'],
    'seen': ['direct', 'indirect'],
})
outer = planets.merge(later, on='method', how='outer')
print(len(outer), outer['year'].isna().sum())
1036 1

The row of Disk Kinematics comes in with NaN in every column of planets, so the result has 1,035 + 1 = 1,036 rows; how='left' would have dropped it.

JOIN and merge

In the weather practice of SQL, the table days of the bike-share system holds a weather code for each day, weather_types holds the name of each code, and this query showed the name next to each day:

SELECT d.observation_date, w.weather_name, d.total_rides
FROM days d
INNER JOIN weather_types w ON d.weather_id = w.weather_id;
days = pd.read_csv('bike-share-days-coded.csv')
weather = pd.read_csv('bike-share-weather-types.csv')
both = days.merge(weather, on='weather_id')
print(len(days), len(both))
print(both[['observation_date', 'weather_name']].head(2))
731 731
  observation_date    weather_name
0       2011-01-01  Mist or cloudy
1       2011-01-02  Mist or cloudy

ON d.weather_id = w.weather_id becomes on='weather_id'; when the names of the keys differ, left_on and right_on name them.
INNER JOIN is the default of merge, LEFT JOIN is how='left', and FULL OUTER JOIN is how='outer'.
The result stays in the variable both, so we check it with len before the next step.

Repeated rows: duplicated

The answer for the panel, like the counts of New columns and groups in pandas and of Groups by two columns and pivot tables in pandas, counts rows:
20 of the 406 rows of the 2000s are planets seen directly. If two rows record one planet, the planets are fewer than the rows.
The method duplicated() returns a mask that is True for a repeated row, a row equal in every column to a row above it; the first of the equal rows is False.
With keep=False every one of the equal rows is True, which shows them all:

print(planets.duplicated().sum())
print(planets[planets.duplicated(keep=False)])
4
           method  number  orbital_period  mass  distance  year
33        Imaging       1             NaN   NaN       NaN  2008
902  Microlensing       1             NaN   NaN       NaN  2008
903  Microlensing       1             NaN   NaN       NaN  2008
904  Microlensing       1             NaN   NaN       NaN  2009
923  Microlensing       1             NaN   NaN       NaN  2009
925  Microlensing       2             NaN   NaN    4080.0  2012
926  Microlensing       2             NaN   NaN    4080.0  2012
957       Imaging       1             NaN   NaN       NaN  2008

Four rows repeat an earlier row: three of microlensing and one of imaging.
In all eight the orbital period and the mass are missing.

Formulate. Rows 925 and 926 are equal in every column. Are they two records of one planet, or two planets?
What in the table could decide it?

Show a hint

The column number is the number of planets known in the planet’s system.
Look for other microlensing rows with the same number and year.

Show the answer
print(planets.loc[[921, 922, 925, 926]])
           method  number  orbital_period  mass  distance  year
921  Microlensing       2          1825.0   NaN       NaN  2008
922  Microlensing       2          5100.0   NaN       NaN  2008
925  Microlensing       2             NaN   NaN    4080.0  2012
926  Microlensing       2             NaN   NaN    4080.0  2012

Rows 921 and 922 are two different planets: the same method, number 2 and the same year, but different orbital periods.
Rows 925 and 926 fit the same pattern, with no orbital period that could tell them apart.
The table has no column that names the planet, a key like the primary key of the SQL lessons, so it cannot decide:
equal rows are not proof of one planet counted twice.

Removing repeated rows: drop_duplicates

The method drop_duplicates() returns a new table without the rows that duplicated() marks:

unique_rows = planets.drop_duplicates()
print(len(unique_rows))
print(unique_rows['method'].value_counts().loc['Microlensing'])
1031
20

Microlensing has 23 rows, 3 of them equal to earlier rows, so it found between 20 and 23 of the planets of the table, and the table alone does not say how many.
This closes the question of the opening: imaging has 38 rows, 37 or 38 planets, so the 20 rows seen directly in the 2000s are 19 or 20 planets of 403 to 406.
The panel gives the counts of rows and says that 4 rows of the table are identical to others.
A removal of repeated rows is right when an equal row means the same record, which a key or the source has to establish.

Rows that look alike: subset and keep

Both methods take subset, the columns that should identify a row, and keep:
'first' (the default) keeps the first of the equal rows, 'last' the last, and False none.
Rows that agree on a few columns are often different rows:

key = ['method', 'number', 'year']
print(planets.duplicated(subset=key).sum())
print(cars.duplicated(subset=['name']).sum())
same_year = cars.duplicated(
    subset=['name', 'model_year'], keep=False,
)
cols = ['name', 'model_year', 'cylinders', 'horsepower', 'mpg']
print(cars[same_year][cols])
891
93
                 name  model_year  cylinders  horsepower   mpg
168        ford pinto          75          4        83.0  23.0
174        ford pinto          75          6        97.0  18.0
338  plymouth reliant          81          4        84.0  27.2
342  plymouth reliant          81          4        84.0  30.0

891 rows share their method, number and year with an earlier row, and 93 rows repeat the name of an earlier car (56 names appear more than once), mostly in other years.
Even the name and the year do not identify a car: the two 1975 Ford Pintos have 4 and 6 cylinders, and the two 1981 Plymouth Reliants differ in fuel economy.

Practice

Your turn. Print the number of different car names in cars, counting each name once.

# your code here
Show a hint

drop_duplicates takes the same argument subset as duplicated.

Show a solution
print(len(cars.drop_duplicates(subset=['name'])))
305
Show a common mistake and why it happens
print(len(cars.drop_duplicates()))

Without subset a row is removed only when it equals another row in every column; no two rows of cars are equal in all of them, so all 398 remain.

Keep in mind

  • pd.DataFrame with a dictionary builds a small table, such as a lookup table: the keys of the dictionary are the names of the columns, and their values the lists of the values.
  • merge(other, on='key', how=...) adds the columns of the matching row: how='inner', the default, drops a row with no match, how='left' keeps it with NaN, and how='outer' keeps the rows of both tables. on, left_on and right_on correspond to the ON of SQL.
  • Count the rows before and after every merge. A lookup table must have each key once: a repeated key multiplies rows, and validate='many_to_one' stops such a merge.
  • A key with no match, or spelled differently, is dropped without a message by an inner merge.
  • duplicated() and drop_duplicates() compare whole rows, or the columns in subset; equal rows are the same record only when a key or the source says so.