Lesson

New Columns and Groups in pandas

A column computed from other columns and a rule applied with apply, on real car models; then one summary for each group of rows, on real planets outside the Solar System: groupby with one statistic, the grouped result and reset_index, size against count, agg, the size of a group next to its mean, and GROUP BY of SQL next to groupby.

Last updated:


In this lesson we learn to add to a table a column computed from other columns, with arithmetic on whole columns or with apply, and then to split the rows of a table into groups and compute one summary for each group with groupby:
the grouped result and reset_index, size against count, several statistics at once with agg, why the size of a group is read next to its mean, and what groupby does differently from the GROUP BY of SQL.

A column computed from other columns

The answer about the efficient models was given in miles per gallon and in pounds, the units of the file.
A reader who compares cars in liters per 100 km and in kilograms needs columns in those units.

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

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

An assignment to a new column name adds a column, computed from whole columns with no loop, as with arrays.
Fuel use in liters per 100 km is 235.215 / mpg (rounded; the derivation is in fuel use in liters per 100 kilometers), and a pound is 0.45359237 kg:

cars['l_per_100km'] = 235.215 / cars['mpg']
cars['weight_kg'] = cars['weight'] * 0.45359237
cols = ['name', 'l_per_100km', 'weight_kg']
print(cars[cols].head(3).round(1))
litres = cars['l_per_100km']
print(cars[litres == litres.min()][cols])
                        name  l_per_100km  weight_kg
0  chevrolet chevelle malibu         13.1     1589.4
1          buick skylark 320         15.7     1675.1
2         plymouth satellite         13.1     1558.5
          name  l_per_100km   weight_kg
322  mazda glc     5.047532  957.079901

The method round(1) rounds the values that are shown; the columns keep all the digits, as the last row shows.
That row comes from a mask that compares a column with its own minimum:
it keeps the row of the smallest value without sorting, and unlike head(1) after a sort it keeps every row that ties for that value.
In the units of the reader, the most efficient model, the Mazda GLC, uses about 5.0 liters per 100 km and weighs about 957 kg.

Practice

Your turn. The power-to-weight ratio of a car is its horsepower per tonne (1000 kg) of weight.
Add to cars a column of horsepower per tonne, computed from the columns horsepower and weight_kg, and print its mean, rounded to one digit after the decimal point.

# your code here
Show a hint

A tonne is 1000 kg, so the weight in tonnes is cars['weight_kg'] / 1000.

Show a solution
tonnes = cars['weight_kg'] / 1000
cars['hp_per_tonne'] = cars['horsepower'] / tonnes
print(round(cars['hp_per_tonne'].mean(), 1))
76.8

The six models without horsepower get NaN in the new column, and mean() skips them.

Show a common mistake and why it happens
tonnes = cars['weight'] / 1000
cars['hp_per_tonne'] = cars['horsepower'] / tonnes
print(round(cars['hp_per_tonne'].mean(), 1))

The column weight is in pounds, so this is horsepower per 1000 pounds, 34.8.
A kilogram is about 2.2 pounds, so the ratio per tonne is larger.

A function on every value: apply

Some rules are not arithmetic on a column. The maker of a car is the first word of its name, and the method split() of a text returns a list of its words.
The method apply of a Series calls a function on each value and returns a Series of the results; the function is often written in place as a lambda:

make = cars['name'].apply(lambda name: name.split()[0])
print(make.value_counts().head(3))
name
ford         51
chevrolet    43
plymouth     31
Name: count, dtype: int64

The first word is the maker as the file writes it, and the file writes one maker in several ways:
Volkswagen appears as volkswagen, vw and vokswagen. A count by such a column is checked before it is used.

apply runs a Python function once for every row. For arithmetic, an expression on the whole column, such as 235.215 / cars['mpg'], is shorter and faster; apply is for a rule that cannot be written as such an expression.

Practice

Your turn. How many car models have a name of more than two words?
Use apply with a lambda, and print the number.

# your code here
Show a hint

Write a function that returns the number of words of one name, with split() as in the box above.

Show a solution
words = cars['name'].apply(lambda name: len(name.split()))
print((words > 2).sum())
197
Show a common mistake and why it happens
words = cars['name'].apply(lambda name: len(name))
print((words > 2).sum())

The function len of a text counts its characters and not its words, so every name has more than two and the program prints 398, the number of all the models.

How were the planets found, and how did that change?

A planetarium team prepares an exhibit on planets outside the Solar System and asks:
by which methods were the known planets found, what kind of planets does each method find, and how did the methods change over the years?
The table exoplanets.csv holds 1,035 rows, one for each planet found until 2014 as listed in NASA’s exoplanet catalogue, in the copy of the seaborn-data repository (file description, with its source and the acknowledgement that the NASA Exoplanet Archive asks for):
the method that found it, the planets known in its system, its orbital period (the days of one orbit around its star), its mass in masses of Jupiter, its distance in parsecs (a parsec is about 3.26 light-years) and the year of discovery.

planets = pd.read_csv('exoplanets.csv')
print(planets.shape)
print(planets['orbital_period'].mean())
(1035, 6)
2002.9175960947582

One method at a time

One mean orbital period of about 2,003 days for all the planets mixes ten methods.
With the tools of Tables in pandas, a filter answers for one method:

transit = planets[planets['method'] == 'Transit']
print(len(transit), transit['orbital_period'].mean())
397 21.102072671259446

That is one line for each of the ten methods, and another round of ten lines for each question about years or masses; a method that we forget to write is a group that we never see.
We want one command that finds the groups by itself and returns one summary for each.

Split, apply, combine

We take six real planets of the table, two from each of three methods:
the list of labels inside loc picks the rows, and the list of names picks the columns.

small = planets.loc[
    [0, 1, 91, 92, 47, 72],
    ['method', 'orbital_period'],
]
print(small)
             method  orbital_period
0   Radial Velocity      269.300000
1   Radial Velocity      874.774000
91          Transit        1.508956
92          Transit        1.742994
47          Imaging     6000.000000
72          Imaging     4639.150000

Predict. Without running anything, write the mean orbital period of each method in small, rounded to one digit after the decimal point.

Show a hint

Put the rows of each method together.

Show a solution
MethodOrbital periodsMean
Radial Velocity269.3, 874.774572.0
Transit1.508956, 1.7429941.6
Imaging6000.0, 4639.155319.6

What we did by hand has three steps, and they have a name: split, apply, combine.
Split the rows into groups by the value of a column; apply a summary to each group on its own; combine the results into one small table, one row for each group.
In pandas the three steps are one line:

by_small = small.groupby('method')['orbital_period']
print(by_small.mean().round(1))
method
Imaging            5319.6
Radial Velocity     572.0
Transit               1.6
Name: orbital_period, dtype: float64

small.groupby('method') splits by the method, ['orbital_period'] picks the column to summarize, and mean() is the summary of each group.

groupby and one statistic

On all 1,035 rows, the method size() counts the rows of each group, and mean() of a column averages it:

by_method = planets.groupby('method')
print(by_method.size())
period = by_method['orbital_period'].mean()
print(period.round(1))
method
Astrometry                         2
Eclipse Timing Variations          9
Imaging                           38
Microlensing                      23
Orbital Brightness Modulation      3
Pulsar Timing                      5
Pulsation Timing Variations        1
Radial Velocity                  553
Transit                          397
Transit Timing Variations          4
dtype: int64
method
Astrometry                          631.2
Eclipse Timing Variations          4751.6
Imaging                          118247.7
Microlensing                       3153.6
Orbital Brightness Modulation         0.7
Pulsar Timing                      7343.0
Pulsation Timing Variations        1170.0
Radial Velocity                     823.4
Transit                              21.1
Transit Timing Variations            79.8
Name: orbital_period, dtype: float64

The decade of a year is the year without its last digit: // keeps the whole part of a division, so 2007 // 10 * 10 is 2000.
A computed column, as in the section above, holds it, and the mean year of discovery of each method says when it was used:

planets['decade'] = planets['year'] // 10 * 10
print(planets.groupby('decade').size())
print(by_method['year'].mean().round(1))
decade
1980      1
1990     31
2000    406
2010    597
dtype: int64
method
Astrometry                       2011.5
Eclipse Timing Variations        2010.0
Imaging                          2009.1
Microlensing                     2009.8
Orbital Brightness Modulation    2011.7
Pulsar Timing                    1998.4
Pulsation Timing Variations      2007.0
Radial Velocity                  2007.5
Transit                          2011.2
Transit Timing Variations        2012.5
Name: year, dtype: float64

The answer for the planetarium

Radial Velocity, which measures the back-and-forth motion of a star pulled by its planet, has 553 rows of the table, and Transit, which measures the dimming of a star when a planet passes in front of it, has 397; the other eight methods together have 85.
The planets of Transit have a mean orbital period of 21.1 days, against 823.4 for Radial Velocity:
in this table, Transit finds planets with short orbits. The table has 1 row from the 1980s, 31 from the 1990s, 406 from the 2000s and 597 from the 2010s, and the mean year of a Transit discovery is 3.7 years later than that of Radial Velocity.
These are descriptions of the table: they do not say why one method finds short orbits, and a planet that no method could find is not in the table at all.

The groups come out in the alphabetical order of their labels, unless we sort the result.

Practice

Your turn. For each method, print the latest year in which it found a planet, as a Series, with groupby and one statistic.

# your code here
Show a hint

Which statistic of a year is its latest?

Show a solution
print(planets.groupby('method')['year'].max())
method
Astrometry                       2013
Eclipse Timing Variations        2012
Imaging                          2013
Microlensing                     2013
Orbital Brightness Modulation    2013
Pulsar Timing                    2011
Pulsation Timing Variations      2007
Radial Velocity                  2014
Transit                          2014
Transit Timing Variations        2014
Name: year, dtype: int64
Show a common mistake and why it happens
print(planets.groupby('method').max())

Without a column after groupby, max() is computed for every column of the table, so the result is a table of six columns and not the years alone.

The grouped result

The result of groupby with one column and one statistic is a Series, a column with labels, as in Tables in pandas.
Its labels are the groups, and pandas keeps them in the attribute index, the index of a table from that lesson; one value is read by its label with loc:

print(list(period.index)[:3])
print(round(period.loc['Transit'], 1))
['Astrometry', 'Eclipse Timing Variations', 'Imaging']
21.1

To use the result as a table, for example to sort it by a column or to add columns to it, reset_index turns the labels into an ordinary column.
On a Series, its argument name names the column of the values:

period_table = period.reset_index(name='mean_period')
print(period_table.round(1).head(3))
print(period_table.shape)
                      method  mean_period
0                 Astrometry        631.2
1  Eclipse Timing Variations       4751.6
2                    Imaging     118247.7
(10, 2)

The methods are now a column method, and the rows have the labels 0 to 9.

Practice

Your turn. The variable period holds the mean orbital period of each method.
Print the mean of the method Radial Velocity, rounded to a whole number with round.

# your code here
Show a hint

The labels of period are written as in the table: print list(period.index) to see them.

Show a solution
print(round(period.loc['Radial Velocity']))
823
Show a common mistake and why it happens
print(round(period.iloc[1]))

The selection by position, iloc, takes the second row, and the groups are in alphabetical order:
the second label is Eclipse Timing Variations. A label is read with loc.

size and count

The mass is missing in 522 rows of the table, and read_csv writes each empty cell as NaN, the missing number of NumPy arrays, which NumPy prints as nan.
Two ways of counting the rows of each method give different numbers:

print(by_method.size().head(4))
print(by_method['mass'].count().head(4))
method
Astrometry                    2
Eclipse Timing Variations     9
Imaging                      38
Microlensing                 23
dtype: int64
method
Astrometry                   0
Eclipse Timing Variations    2
Imaging                      0
Microlensing                 0
Name: mass, dtype: int64

Formulate. For Imaging, size() gives 38 and count() of the mass gives 0.
What does each of the two count?

Show a hint

Look for an Imaging planet with a mass in the table.

The formal definition

size() counts the rows of each group; count() on a column counts the values of that column that are not missing, so it skips NaN.
The number of missing values of each group is size() - count(). pandas computes on two Series by label:
it pairs the values that have the same label, here the same method, and subtracts each pair:

missing = by_method.size() - by_method['mass'].count()
print(missing)
method
Astrometry                         2
Eclipse Timing Variations          7
Imaging                           38
Microlensing                      23
Orbital Brightness Modulation      3
Pulsar Timing                      5
Pulsation Timing Variations        1
Radial Velocity                   43
Transit                          396
Transit Timing Variations          4
dtype: int64

A question “how many rows” is answered by size(); “how many rows have a mass” by count().

Several statistics with agg

Besides mean(), a group has min(), max() and sum(), and agg computes several of them at once:
a list of their names gives one column for each.

stats = by_method['orbital_period'].agg(
    ['mean', 'min', 'max'],
)
print(stats.round(1))
                                   mean     min       max
method                                                   
Astrometry                        631.2   246.4    1016.0
Eclipse Timing Variations        4751.6  1916.2   10220.0
Imaging                        118247.7  4639.2  730000.0
Microlensing                     3153.6  1825.0    5100.0
Orbital Brightness Modulation       0.7     0.2       1.5
Pulsar Timing                    7343.0     0.1   36525.0
Pulsation Timing Variations      1170.0  1170.0    1170.0
Radial Velocity                   823.4     0.7   17337.5
Transit                            21.1     0.4     331.6
Transit Timing Variations          79.8    22.3     160.0

The orbits of Transit planets range from less than half a day to 331.6 days; the longest orbit of Imaging, 730,000 days, is about 2,000 years.

A column of agg can also get a name of our own: each argument name='statistic' makes a column with that name.
Here size is a statistic as well:

summary = by_method['orbital_period'].agg(
    planets='size', mean_period='mean',
)
print(summary.round(1).head(4))
                           planets  mean_period
method                                         
Astrometry                       2        631.2
Eclipse Timing Variations        9       4751.6
Imaging                         38     118247.7
Microlensing                    23       3153.6

Practice

Your turn. For each method, print the smallest and the largest distance from the Sun in parsecs, in this order, with agg, rounded to one digit after the decimal point.

# your code here
Show a hint

agg takes a list of statistics, and their order is the order of the columns.

Show a solution
print(by_method['distance'].agg(['min', 'max']).round(1))
                                  min     max
method                                       
Astrometry                       15.0    20.8
Eclipse Timing Variations       130.7   500.0
Imaging                           7.7   165.0
Microlensing                   1760.0  7720.0
Orbital Brightness Modulation  1180.0  1180.0
Pulsar Timing                  1200.0  1200.0
Pulsation Timing Variations       NaN     NaN
Radial Velocity                   1.4   354.0
Transit                          38.0  8500.0
Transit Timing Variations       339.0  2119.0

The method with one row has no distance in the table, so both of its values are NaN.

Show a common mistake and why it happens
print(planets['distance'].agg(['min', 'max']).round(1))

Without groupby the statistics are of the whole column, so the result is one smallest and one largest distance of all the rows, not one pair for each method.

The size of a group next to its mean

The longest mean orbit after Imaging is that of Pulsar Timing, 7,343.0 days.
The five values of the group show what this mean rests on; tolist() returns the values of a column as a list:

pulsar = planets[planets['method'] == 'Pulsar Timing']
print(pulsar['orbital_period'].round(1).tolist())
[25.3, 66.5, 98.2, 36525.0, 0.1]

Pulsar Timing has 5 rows, and one of them has an orbit of 36,525 days, exactly 100 years, a round number that looks like a rough estimate; without it the other four are below 100 days.
Pulsation Timing Variations has one row and Astrometry two, so their “means” are one or two measurements.
A grouped mean is read with the size of its group next to it.

GROUP BY and groupby

The SQL lessons asked the bike-share days for the mean number of rides in each season.
The same question in SQL and in pandas, on the same 731 days in bike-share-days.csv:

SELECT season, AVG(total_rides)
FROM daily_ridership
GROUP BY season;
days = pd.read_csv('bike-share-days.csv')
by_season = days.groupby('season')['total_rides'].mean()
print(by_season.round(1))
season
Fall      4728.2
Spring    4992.3
Summer    5644.3
Winter    2604.1
Name: total_rides, dtype: float64

The column after GROUP BY is the argument of groupby, and the summary function AVG(total_rides) is the column in square brackets with mean().
What differs:

SQLpandas
The query returns rows to readThe result is a Series in a variable, for the next step
The group column is written in SELECTThe groups are the labels of the result
Rows come in a set order only with ORDER BYGroups come sorted by label; sort_values sorts by value
HAVING keeps groupsA mask on the result keeps groups: by_season[by_season > 5000]

Keep in mind

  • A new column is an assignment of an expression on whole columns, with no loop; apply with a lambda is for a rule that cannot be written as such an expression.
  • df.groupby('column')['measure'].mean() splits the rows by the values of a column, summarizes each group and combines the results: the GROUP BY of SQL, with the result kept in a variable.
  • The result of one statistic is a Series whose labels are the groups, in the order of the labels unless sorted; a value is read with loc['label'], and reset_index turns the groups into a column.
  • size() counts rows; count() counts the values that are not missing. The number of missing values of each group is size() - count().
  • agg(['mean', 'min', 'max']) gives several statistics at once, and agg(name='statistic') names the columns.
  • A mean of a small group moves a lot with one row: read the size of each group next to its mean.