4. Joining Tables by Columns

Often, data about the same individuals is maintained in more than one table. For example, one university office might have data about each student’s time to completion of degree, while another has data about the student’s tuition and financial aid.

To understand the students’ experience, it may be helpful to put the two datasets together. If the data are in two tables, each with one row per student, then we would want to put the columns together, making sure to match the rows so that each student’s information remains on a single row.

Let us do this in the context of a simple example, and then use the method with a larger dataset.

Pandas Merge, Join, Concatenate

The table cones is one we have encountered earlier. Now suppose each flavor of ice cream comes with a rating that is in a separate table.

cones = pd.DataFrame(
    {'Flavor':np.array(['strawberry', 'vanilla', 'chocolate', 'strawberry', 'chocolate']),
    'Price':np.array([3.55, 4.75, 6.55, 5.25, 5.75])}
)
cones
Flavor Price
0 strawberry 3.55
1 vanilla 4.75
2 chocolate 6.55
3 strawberry 5.25
4 chocolate 5.75
ratings = pd.DataFrame(
    {'Kind':np.array(['strawberry', 'chocolate', 'vanilla']),
    'Stars':np.array([2.5, 3.5, 4])}
)
ratings
Kind Stars
0 strawberry 2.5
1 chocolate 3.5
2 vanilla 4.0

Each of the tables has a column that contains ice cream flavors: cones has the column Flavor, and ratings has the column Kind. The entries in these columns can be used to link the two tables.

The method join creates a new table in which each cone in the cones table is augmented with the Stars information in the ratings table. For each cone in cones, join finds a row in ratings whose Kind matches the cone’s Flavor.

In this instance we are going to join two df’s by joining key columns on an index. To implement a join on an index we must create the index we wish to use in the second df, then we have to tell join to use those columns for matching.

Pandas - key columns

cones = pd.DataFrame(
    {'Flavor':np.array(['strawberry', 'vanilla', 'chocolate', 'strawberry', 'chocolate']),
    'Price':np.array([3.55, 4.75, 6.55, 5.25, 5.75])}
)

ratings = pd.DataFrame(
    {'Kind':np.array(['strawberry', 'chocolate', 'vanilla']),
     'Stars':np.array([2.5, 3.5, 4])},
                      index=np.array(['strawberry', 'chocolate', 'vanilla']))

rates = cones.join(ratings, on='Flavor')

rates
Flavor Price Kind Stars
0 strawberry 3.55 strawberry 2.5
1 vanilla 4.75 vanilla 4.0
2 chocolate 6.55 chocolate 3.5
3 strawberry 5.25 strawberry 2.5
4 chocolate 5.75 chocolate 3.5

This will create a df which includes the ‘Kind’ column i.e. we are repeating the flavours. To display only the columns in which we are interested -

#rated = rates[['Flavor', 'Price', 'Stars']].sort_values(by=(['Flavor']))

#or

rated = rates.drop(columns=['Kind'])

rated
Flavor Price Stars
0 strawberry 3.55 2.5
1 vanilla 4.75 4.0
2 chocolate 6.55 3.5
3 strawberry 5.25 2.5
4 chocolate 5.75 3.5

Each cone now has not only its price but also the rating of its flavor.

In general, a call to join that augments a table (say table1) with information from another table (say table2) looks like this:

table1.join(table2, table1_column_for_joining)

The new table rated allows us to work out the price per star, which you can think of as an informal measure of value. Low values are good – they mean that you are paying less for each rating star.

rated['$/Price'] = rated['Price'] / rated['Stars']

rated.sort_values('$/Price')
Flavor Price Stars $/Price
1 vanilla 4.75 4.0 1.187500
0 strawberry 3.55 2.5 1.420000
4 chocolate 5.75 3.5 1.642857
2 chocolate 6.55 3.5 1.871429
3 strawberry 5.25 2.5 2.100000

Though strawberry has the lowest rating among the three flavors, the less expensive strawberry cone does well on this measure because it doesn’t cost a lot per star.

Side note. Does the order we list the two tables matter? Let’s try it. As you see it, this changes the order that the columns appear in, and can potentially changes the order of the rows, but it doesn’t make any fundamental difference.

cones1 = pd.DataFrame(
    {'Flavor':np.array(['strawberry', 'vanilla', 'chocolate', 'strawberry', 'chocolate']),
    'Price':np.array([3.55, 4.75, 6.55, 5.25, 5.75])},
    index=np.array(['strawberry', 'vanilla', 'chocolate', 'strawberry', 'chocolate'])
)

ratings = pd.DataFrame(
    {'Kind':np.array(['strawberry', 'chocolate', 'vanilla']),
     'Stars':np.array([2.5, 3.5, 4])})

rates = ratings.join(cones1, on='Kind')

rates = rates.drop(columns=['Flavor'])

rates
Kind Stars Price
0 strawberry 2.5 3.55
0 strawberry 2.5 5.25
1 chocolate 3.5 6.55
1 chocolate 3.5 5.75
2 vanilla 4.0 4.75

Also note that the join will only contain information about items that appear in both tables. Let’s see an example. Suppose there is a table of reviews of some ice cream cones, and we have found the average or mean of reviews for each flavor.

reviews = pd.DataFrame(
    {'Flavor':np.array(['vanilla', 'chocolate', 'vanilla', 'chocolate']),
    'Stars':np.array([5, 3, 5, 4])}
)
reviews
Flavor Stars
0 vanilla 5
1 chocolate 3
2 vanilla 5
3 chocolate 4
average_review = reviews.groupby('Flavor').mean()

average_review = average_review.rename(columns={'Stars':'Stars average'})

average_review
Stars average
Flavor
chocolate 3.5
vanilla 5.0

We can join cones and average_review by providing the labels of the columns by which to join.

reviewers = cones.join(average_review, on='Flavor')

reviewers = reviewers.rename(columns={'Stars':'Stars average'})

reviewers = reviewers.dropna()

reviewers.sort_values(['Stars average'])
Flavor Price Stars average
2 chocolate 6.55 3.5
4 chocolate 5.75 3.5
1 vanilla 4.75 5.0

Notice how the strawberry cones have disappeared. None of the reviews are for strawberry cones, so there is nothing to which the strawberry rows can be joined. This might be a problem, or it might not be - that depends on the analysis we are trying to perform with the joined table.