Lesson

Groups by Two Columns and Pivot Tables in pandas

A summary by two columns, on real exoplanet discoveries, real car models and Iowa electricity generation: groupby with two columns and labels in two levels, the top groups, a question in four steps, pivot_table with aggfunc and fill_value, an empty cell, a mean in each cell, and a long table of records turned into a wide one.

Last updated:


In this lesson we learn to group rows by two columns and to show such a summary as a table of rows by columns with pivot_table:
an empty cell and fill_value; then to find the top groups, to answer a question in a chain of steps, to put a mean in each cell, and to turn a long table of records into a wide one.

How many planets did each method find, decade by decade?

The planetarium team of New columns and groups in pandas wants one table for a wall of the exhibit:
for each discovery method, how many planets it found in each decade.
The answer of that page counted the rows of each method and of each decade separately; the wall needs the two together.
The data are the same table, exoplanets.csv, with the column decade computed as there, and the practice uses also the car models of Tables in pandas.

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')
planets['decade'] = planets['year'] // 10 * 10
cars = pd.read_csv('auto-mpg.csv')
print(planets.shape, cars.shape)
(1035, 7) (398, 9)

Groups by two columns

A list of two columns makes a group for each pair of values that occurs.
Two columns are given as one list; written as two separate arguments, groupby('decade', 'method'), they stop the program with an error.
The two main methods, kept with isin, by decade:

two = ['Radial Velocity', 'Transit']
main = planets[planets['method'].isin(two)]
by_decade = main.groupby(['decade', 'method']).size()
print(by_decade)
decade  method         
1980    Radial Velocity      1
1990    Radial Velocity     28
2000    Radial Velocity    309
        Transit             62
2010    Radial Velocity    215
        Transit            335
dtype: int64

The labels now have two levels, labels in two levels: the decade, and inside it the method.
One value is read with a pair of labels, loc[(2010, 'Transit')], and one label of the first level returns all its groups:

print(by_decade.loc[(2010, 'Transit')])
print(by_decade.loc[2000])
335
method
Radial Velocity    309
Transit             62
dtype: int64

Transit has 62 rows in the 2000s and 335 in the 2010s, more than Radial Velocity in the same years:
this is how the methods changed in the table.

Practice

The car models of auto-mpg.csv, read into cars in the first box of this page, give a second case.

Your turn. For each origin of the car models and, inside it, for each number of cylinders, print the number of car models, with groupby.

# your code here
Show a hint

The first column in the list of groupby is the outer level.

Show a solution
print(cars.groupby(['origin', 'cylinders']).size())
origin  cylinders
europe  4             63
        5              3
        6              4
japan   3              4
        4             69
        6              6
usa     4             72
        6             74
        8            103
dtype: int64
Show a common mistake and why it happens
by_cyl = cars.groupby(['origin', 'cylinders'])
print(by_cyl['horsepower'].count())

The method count() of the horsepower skips the 6 models without a horsepower, so three groups get smaller numbers, for example 61 four-cylinder models from Europe instead of 63.
The number of models of a group is its size().

A table of methods by decades: pivot_table

The list by_decade holds two methods; for all ten it would have 19 lines, and to compare the methods within the 2000s we would collect them from all over the list.
A pair with no planet has no line at all: Transit has no line for the 1990s.
The wall needs the methods as rows and the decades as columns, with the number of rows of the pair in each cell.
Such a table is a pivot table.

Predict. How many rows and how many columns will a table of the methods by the decades have, and what should the cell of astrometry and the 1990s hold?

Show a hint

Count the different methods and the different decades, as size() by method and by decade listed them in New columns and groups in pandas.

Show a solution

10 rows, one for each method, and 4 columns, for the decades 1980 to 2010.
Astrometry found no planet in the 1990s, so the number in its cell is 0.

The method pivot_table of a table builds it. Its arguments say what goes where:

  • index: the column whose values become the labels of the rows;
  • columns: the column whose values become the labels of the columns;
  • aggfunc: the summary computed on the rows of each cell, by name, as in agg; 'size' counts the rows.
counts = planets.pivot_table(
    index='method', columns='decade', aggfunc='size',
)
print(counts)
decade                         1980  1990   2000   2010
method                                                 
Astrometry                      NaN   NaN    NaN    2.0
Eclipse Timing Variations       NaN   NaN    3.0    6.0
Imaging                         NaN   NaN   20.0   18.0
Microlensing                    NaN   NaN   10.0   13.0
Orbital Brightness Modulation   NaN   NaN    NaN    3.0
Pulsar Timing                   NaN   3.0    1.0    1.0
Pulsation Timing Variations     NaN   NaN    1.0    NaN
Radial Velocity                 1.0  28.0  309.0  215.0
Transit                         NaN   NaN   62.0  335.0
Transit Timing Variations       NaN   NaN    NaN    4.0

The cell of a pair that has no planet is empty: it holds NaN, a number of the type float, so the whole table is written with a decimal point.

A cell for a pair that does not occur

In a table of counts, an empty cell is a pair of a method and a decade that does not occur in the data:
no planet, not a measurement that is missing. The number of its planets is 0, and the argument fill_value=0 writes it:

counts = planets.pivot_table(
    index='method', columns='decade', aggfunc='size',
    fill_value=0,
)
print(counts)
decade                         1980  1990  2000  2010
method                                               
Astrometry                        0     0     0     2
Eclipse Timing Variations         0     0     3     6
Imaging                           0     0    20    18
Microlensing                      0     0    10    13
Orbital Brightness Modulation     0     0     0     3
Pulsar Timing                     0     3     1     1
Pulsation Timing Variations       0     0     1     0
Radial Velocity                   1    28   309   215
Transit                           0     0    62   335
Transit Timing Variations         0     0     0     4

This is the table for the wall. In the 2000s, radial velocity has 309 of the 406 rows of the table and transits 62; in the column 2010, transits have 335 rows and radial velocity 215.
The file stops in 2014, so the column 2010 holds five years, 2010 to 2014, against ten years in the column 2000.

pivot_table and groupby

Formulate. Compare counts with the list by_decade of groups by two columns.
How is each cell of counts obtained from such a list, and where do the zeros come from?

Show a hint

Find the line of 2010 and Transit in by_decade, and the cell of the row Transit and the column 2010 in counts.

The formal definition

pivot_table(index='a', columns='b', aggfunc=f) groups the rows by the pairs of values of a and b, as groupby(['a', 'b']) does, applies f to each group, and writes the result of the pair (x, y) in the row x and the column y.
A pair that has no rows has no group, so its cell is empty, or holds fill_value.

A cell is read with loc[row, column], as in tables in pandas.
The labels of the columns are the numbers of the decades, so the column is written 2010 and not '2010'.
The list pairs counts every pair that occurs, with the method first, as in the rows of counts:

pairs = planets.groupby(['method', 'decade']).size()
print(counts.loc['Transit', 2010])
print(pairs.loc[('Transit', 2010)])
print(counts.shape, len(pairs))
335
335
(10, 4) 19

The table has 40 cells and the list pairs 19 lines: 19 pairs occur, and the other 21 cells are the zeros of pairs that do not occur.

Practice

Your turn. For each number of planets known in a system (the column number, rows) and each decade (columns), print the number of rows of the table; write 0 for a pair that does not occur.

# your code here
Show a hint

The values of number label the rows, so number is the argument index.

Show a solution
print(planets.pivot_table(
    index='number', columns='decade', aggfunc='size',
    fill_value=0,
))
decade  1980  1990  2000  2010
number                        
1          1    16   296   282
2          0     6    67   186
3          0     4    24    60
4          0     4    13    15
5          0     1     3    26
6          0     0     3    21
7          0     0     0     7
Show a common mistake and why it happens
print(planets.pivot_table(
    index='number', columns='decade', aggfunc='size',
))

Without fill_value=0, the pairs that do not occur are NaN instead of 0, and the other counts are written with a decimal point.

The top groups

A grouped result is sorted like any Series, with sort_values from Tables in pandas; ascending=False puts the largest first and head(3) keeps three.
The method nlargest(3) returns the same three in one step. The example is the mean orbital period of each method, period of New columns and groups in pandas.

period = planets.groupby('method')['orbital_period'].mean()
print(period.sort_values(ascending=False).head(3).round(1))
method
Imaging                      118247.7
Pulsar Timing                  7343.0
Eclipse Timing Variations      4751.6
Name: orbital_period, dtype: float64

Before the sort the methods were in the order of their labels, and head(3) would have returned the first three in the alphabet.
The method nsmallest returns the smallest values in the same way.

A question in four steps

A question in plain words is often a chain: filter the rows, group them, summarize each group and sort the result.
A long chain can be written inside parentheses, one step on each line.

Your turn. Among the cars with 4 cylinders in cars, print the mean fuel economy in miles per gallon of each origin as a Series, sorted from the highest, rounded to two digits after the decimal point.

# your code here
Show a hint

Filter the rows of cars with a condition on the number of cylinders before grouping.

Show a solution
four = cars[cars['cylinders'] == 4]
print(
    four.groupby('origin')['mpg'].mean()
    .sort_values(ascending=False).round(2)
)
origin
japan     31.60
europe    28.41
usa       27.84
Name: mpg, dtype: float64
Show a common mistake and why it happens
print(
    cars.groupby('origin')['mpg'].mean()
    .sort_values(ascending=False).round(2)
)

Without the filter the means are of all the cars, with 6 and 8 cylinders too, so the American mean falls to 20.08:
most American models of the table have 6 or 8 cylinders.

A mean in each cell

With values and a statistic such as 'mean', each cell holds the mean of a column over the planets of the pair.
The mean distance from the Sun, in parsecs:

dist = planets.pivot_table(
    index='method', columns='decade', values='distance',
    aggfunc='mean',
)
print(dist.round(1))
decade                         1980  1990   2000    2010
method                                                  
Astrometry                      NaN   NaN    NaN    17.9
Eclipse Timing Variations       NaN   NaN  130.7   500.0
Imaging                         NaN   NaN   59.8    75.6
Microlensing                    NaN   NaN    NaN  4144.0
Orbital Brightness Modulation   NaN   NaN    NaN  1180.0
Pulsar Timing                   NaN   NaN    NaN  1200.0
Radial Velocity                40.6  25.8   50.5    56.9
Transit                         NaN   NaN  723.3   569.0
Transit Timing Variations       NaN   NaN    NaN  1104.3

Formulate. The cell of astrometry and 2000 is empty, and so is the cell of microlensing and 2000.
Use counts to say what each of the two empty cells means.

Show a hint

Read the same two cells in counts.

Show a solution

Astrometry found no planet in the 2000s (0 in counts): the pair does not occur.
Microlensing has 10 rows in the 2000s, and none of them has a distance in the table:
the pair occurs, and the measurement is missing. The table has 9 rows and not 10:
the one planet of pulsation timing variations has no distance, and pivot_table drops a row all of whose cells are empty, because its argument dropna is True by default (dropna=False keeps the row).

fill_value=0 would write a mean distance of 0 parsecs in both cells, a value that no planet has.
In a table of means an empty cell stays empty.

Practice

Your turn. For each discovery method (rows) and decade (columns), print the largest mass of a planet, in masses of Jupiter.

# your code here
Show a hint

aggfunc takes the name of a statistic as text, as agg does.

Show a solution
print(planets.pivot_table(
    index='method', columns='decade', values='mass',
    aggfunc='max',
))
decade                      1980  1990   2000   2010
method                                              
Eclipse Timing Variations    NaN   NaN   6.05   4.20
Radial Velocity            11.68  8.44  25.00  20.60
Transit                      NaN   NaN    NaN   1.47

The transits of the 2000s are 62 rows, and none has a mass in the table, so their cell is empty.

Show a common mistake and why it happens
print(planets.pivot_table(
    index='method', columns='decade', values='mass',
    aggfunc='max', fill_value=0,
))

fill_value=0 writes a largest mass of 0.00 in five cells: in four of them there is no planet, and in the fifth, transits of the 2000s, there are 62 rows whose mass is missing.
No planet has a mass of 0.

A long table of records

The second table is the yearly net generation of electricity in the state of Iowa, in thousands of megawatt-hours, by the kind of source, 2001 to 2017, from the U.S. Energy Information Administration (public domain, through the vega-datasets collection).
We want to know in which year renewable sources first generated more electricity than nuclear energy.

elec = pd.read_csv('iowa-electricity.csv')
print(elec.shape)
print(elec[elec['year'] == '2001-01-01'])
(51, 3)
          year          source  net_generation
0   2001-01-01    Fossil Fuels           35361
17  2001-01-01  Nuclear Energy            3853
34  2001-01-01      Renewables            1437

Each row is one record: a year, a source and the generation.
The three numbers of one year are in rows 0, 17 and 34, so comparing two sources year by year means jumping 17 rows each time.
A table with one row for each measurement and the kind of measurement in a column is a long table.

From a long table to a wide one

In a wide table, each year is one row and each source is a column.
The years are written as the first day of the year, as text; str[:4] takes the first four characters of each text, as a slice does for one text, and astype(int) turns them into numbers:

elec['year'] = elec['year'].str[:4].astype(int)
wide = elec.pivot_table(
    index='year', columns='source', values='net_generation',
)
print(wide.loc[2007:2010])
source  Fossil Fuels  Nuclear Energy  Renewables
year                                            
2007         41389.0          4519.0      3870.0
2008         42734.0          5282.0      5070.0
2009         38620.0          4679.0      8560.0
2010         42750.0          4451.0     10308.0

The answer is in two adjacent rows: in 2008 renewables generated 5,070 thousand megawatt-hours against 5,282 of nuclear energy, and in 2009 8,560 against 4,679.

Each cell of wide has exactly one row of elec, so the default summary of pivot_table, the mean, returns that value itself, written as a float.
The method pivot builds the same table without any summary and keeps the integers, but it stops with an error when a pair of a year and a source occurs in two rows.

The whole wide table is 17 rows of 3 numbers. Its first and last rows show the change from 2001 to 2017, and sum(axis=1) adds across each row, as axis does for an array, so it returns the total generation of each year:

print(wide.shape)
print(wide.loc[[2001, 2017]])
print(wide.sum(axis=1).loc[[2001, 2017]])
(17, 3)
source  Fossil Fuels  Nuclear Energy  Renewables
year                                            
2001         35361.0          3853.0      1437.0
2017         29329.0          5214.0     21933.0
year
2001    40651.0
2017    56476.0
dtype: float64

Practice

Your turn. For each year, print the share of renewables in the total net generation of that year, rounded to three digits after the decimal point.

# your code here
Show a hint

The share of a year is the generation of renewables divided by the total of that year.

Show a solution
share = wide['Renewables'] / wide.sum(axis=1)
print(share.round(3))
year
2001    0.035
2002    0.046
2003    0.045
2004    0.049
2005    0.062
2006    0.074
2007    0.078
2008    0.096
2009    0.165
2010    0.179
2011    0.209
2012    0.264
2013    0.291
2014    0.307
2015    0.337
2016    0.391
2017    0.388
dtype: float64
Show a common mistake and why it happens
share = wide['Renewables'] / wide.sum()
print(share.round(3))

Without axis=1, sum() adds each column and returns three totals labelled by the sources. pandas pairs the values of two Series by label, as in size and count.
No year is the label of a source, so every value of the result is NaN.

Keep in mind

  • groupby(['a', 'b']) makes a group for each pair, with labels in two levels: the first column is the outer level.
  • pivot_table(index=..., columns=..., values=..., aggfunc=...) is a summary by two columns shown as a table: the groups of groupby on the two columns, with the second spread across the columns. A cell is read with loc[row, column].
  • An empty cell is a pair that does not occur, or a pair whose values are all missing. fill_value=0 is right for a count and wrong for a mean or a maximum.
  • sort_values(ascending=False).head(n) or nlargest(n) finds the top groups.
  • A question in plain words is often a chain: filter the rows, group them, summarize each group, sort the result.
  • A long table, one row for each record, becomes a wide table with pivot_table; pivot does the same when each pair occurs once.