Housing — the lack of it, and the difficulty in finding an affordable home – has been a major issue in the US presidential election, which takes place in just under two weeks. It's an important enough issue that Kamala Harris has come out with a whole plan aimed at both increasing the supply of housing and reducing the price to first-time buyers. There are many different obstacles in the way of constructing new housing, as a recent episode of NPR's Planet Money from August (https://www.npr.org/2024/08/30/1197961522/minneapolis-minnesota-housing-2040-tim-walz) described.
This week, we're thus looking at data that the US Census Bureau has collected about the number of homes started and completed in each year, both for the United States in general and for each of four regions in the country.
Data and seven questions
This week's data comes from the US Census Bureau's "survey of construction." They offer a variety of data sets, all from this page:
https://www.census.gov/construction/nrc/data/series.html
We will look at two of the data sets from this page:
- Housing units started, https://www.census.gov/construction/nrc/xls/starts_cust.xlsx
- Housing units completed, https://www.census.gov/construction/nrc/xls/comps_cust.xlsx
Yesterday, I posed seven tasks and questions about the data. Here are my solutions; as always, a link to the Jupyter notebook I used to solve these problems is at the end of this post.
Create two data frames, one from each of the two Excel files references above, on the "Annual" tab in both files. The columns should be a two-level multi-index. Values labeled (NA) should be turned into NaN. Ignore the header and footer information. The index (rows) should contain the year from the first column.
Let's start things off by loading Pandas:
import pandas as pdNext, we'll use read_excel to read the Excel file for housing starts into a data frame:
starts_df = (
pd
.read_excel('starts_cust.xlsx')
)This doesn't quite work, for a variety of reasons:
- We need to pass the
sheet_namekeyword argument to get back a particular tab ("sheet") from the document - We want the "year" value to be our index, which we can specify with the
index_colkeyword argument, setting it to 0 to indicate that we want the first column - The headers are spread across two lines (4 and 5, using Pandas's zero-based indexing), so we can pass the
headerkeyword argument, giving it a value of[4,5], a list of integers. This has the added effect of ignoring the unstructured text before row 4. - There is some more unstructured text after the 65th row of data. We can thus pass the
nrowskeyword argument to grab only 65 lines into our data frame. - Finally, the Excel file uses
(NA)to indicate missing values, which we want to have the Pandas valueNaN. We can pass thena_valueskeyword argument, giving it a value of'(NA)', so that those inputs will be treated asNaN.
Putting this all together, we get the following:
starts_df = (
pd
.read_excel('starts_cust.xlsx',
header=[4,5],
sheet_name='Annual',
na_values='(NA)',
nrows=65,
index_col=0)
)The result is a data frame with 65 rows (but we knew that) and 12 columns.
We can do just about the same thing with the completed homes data:
comps_df = (
pd
.read_excel('comps_cust.xlsx',
header=[4,5],
sheet_name='Annual',
na_values='(NA)',
nrows=56,
index_col=0)
)The only real difference here is the number of rows, which reflects the fewer years of data. Indeed, we have 56 rows and (the same) 12 columns.
Create a line plot showing total housing starts and completions in the overall United States. Show starts with a dashed blue line, and completed houses with a solid red line. When did the most recent big changes in the housing market take place?
In order to create such a plot, we'll need to combine the data from the two different data frames we've created. But we don't want all of the data. We just need the "Total" values from the overall United States for each of the data frames.
Let's start by getting the total data for the United States from starts_df:
(
starts_df
[[('United States', 'Total')]]
)There are a few interesting aspects to the above code:
- Because we have a multi-index on our column names, we need to specify both the outer and inner levels in order to grab a particular column. We can do that with a tuple, naming the levels in order, from outside to inside. Note that you cannot use a list, because that would imply that we're trying to do fancy indexing, retrieving multiple columns.
- Normally, we could retrieve our column with a single set of square brackets. But that would return the column as a series. That's not inherently bad, except that we want to use this column as the left side on a "join" operation – and
joinis a method for data frames, not for series. By using double square brackets, we get back a data frame, albeit one with only a single column.
With that narrow data frame, we can invoke join to combine it with another data frame – the result of performing a similar operation on comps_df. Joining works on the index, so it's good (and not a coincidence!) that we already have the indexes set to the be the years in each data frame:
(
starts_df
[[('United States', 'Total')]]
.join(comps_df[('United States', 'Total')],
lsuffix='_starts', rsuffix='_comps')
)Notice that I passed the lsuffix and rsuffix keyword arguments to join. Whereas a data frame's index can have repeated values, the columns cannot. When we join two similar or identical data frames together, the resulting (new) data frame cannot have any repeated columns; we'll get an error message from Pandas. The lsuffix and rsuffix keyword arguments tell Pandas what strings to add to the column names that originated on the left and the right, so that the query can complete successfully.
Note that because comps_df has less data than starts_df, and because we performed the join using starts_df, the first few rows of the comps column contains NaN. That's not really an issue for us, but you will see a shorter line for completions.
Finally, we can create a line plot with plot.line. But I asked you to display the lines in a particular way, with a blue dashed line. If you pass the style keyword argument to plot.line, it is passed along to Matplotlib, which uses it to style the output. That style string should contain as many space-separated, three-character "words" as there are columns in the data frame, each of which specifies a color, a marker type, and a line type.
The full specification is here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
In this case, I chose blue (b), dots (.), and a dashed line (:) for the first line, and a red line (r) with x markers (x) and a regular line (-):
(
starts_df
[[('United States', 'Total')]]
.join(comps_df[('United States', 'Total')],
lsuffix='_starts', rsuffix='_comps')
.plot.line(style='b.: rx-'.split())
)The result:

I asked when the most recent changes in housing starts and completions took place. There was a small drop in housing starts in 2020, and the US hasn't recovered from it. But even that peak was lower than what we see from about 2005, just before the 2008 housing crisis plunged US real estate into crisis. Indeed, I've heard numerous reports saying that oversupply of housing after that crisis led to low prices, which pushed home-construction companies out of the business. The US is still suffering from that period.
Create a line plot showing total housing starts in the US as well as each region. Do the regions all appear to move in sync? Where has most housing construction taken place in the last few decades?
Next, I asked you to create a line plot showing total housing starts – in the US, and in each of the four regions that the Census Bureau tracks. In other words, we need the columns where "Total" is the inner part of the multi-indexed columns.
Grabbing columns based on a particular value at a particular level is possible with the xs method. We indicate what value we're looking for — sorry, no patterns or lists of matches will work here – along with the level we want, and the axis (to indicate we aren't using rows). The result:
(
starts_df
.xs('Total', level=1, axis='columns')
)The result is a data frame with 65 rows and five columns, one each for the US, Northeast, Midwest, South, and West. We can then invoke plot.line to plot these against each other:
(
starts_df
.xs('Total', level=1, axis='columns')
.plot.line()
)Here's what I got:

Obviously, the overall United States line (which is the sum of the others) will be higher. But we can see that the regions generally (not always) move in sync with one another, and that most new housing in the last few decades has been built in the South and the West.
Even when things went south (so to speak) during the financial crisis of 2008, and the bottom dropped out of the housing market, more homes were still being built in the South than were built in the Northeast at its peak. Of course, you could argue that the Northeast is crowded, and has less room for housing; people there often buy existing homes, rather than build new ones.
Find, for each decade, the number of total housing starts in the overall US. How do housing starts in the most recent years compare with preceding decades? The US population is now about 330m people, and was 203m in 1970; how might this affect the supply and demand for housing?
starts_df has an index consisting of years (i.e., integers). But if we want to calculate how many houses were constructed per decade, we'll want to use "resampling," a technique that only works when you have datetime data in a data frame's index.
We'll thus create a new datetime column based on the index, and then set it to be the data frame's index. We'll then run resample on that data frame to get the result we want.
First, we'll need to turn the index back into a regular column. We can do that with reset_index:
(
starts_df
.reset_index()
)Next, we'll take the values in the index column (i.e., the years), turn them into strings, and then add '-12-31' to each one. Why? Because we want to turn them into datetime values, passing them to pd.to_datetime. If we just pass the year, then we get datetime values for the first day of each year, namely January 1st. But because the period is measured at the end of each year, December 31st seems more appropriate.
So we take each value in the former index, turn it into a string, add -12-31 to it, and then invoke pd.to_datetime on it. This results in a Pandas series, one which we assign (using the assign method to a new column, called date, which we then turn into the index using set_index:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
)We now have a time series, aka a data frame whose index contains datetime values. But we only want one to perform a calculation on one of the columns from the original data frame. So let's select just one column – but because it's a multi-index, we need to use a tuple to specify both of the levels through which we want to drill down:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
[('United States', 'Total')]
)Finally, now that we have a series with a datetime index, we can invoke resample. We specify the time period we want, namely 1 decade – which we can say is 10YE, meaning 10 periods of "year end." We then use the sum method, because we want to sum up the number of homes built during that time:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
[('United States', 'Total')]
.resample('10YE').sum()
)We get back a series whose index contains the end of each 10-year period, starting with the first data row we have. We thus don't exactly get decades, but rather 10-year periods ending with years ending in "9" – 1959, 1969, etc. Here's what I get:
date
1959-12-31 1517.0
1969-12-31 14063.8
1979-12-31 17675.8
1989-12-31 14923.0
1999-12-31 13713.6
2009-12-31 15363.5
2019-12-31 9933.0
2029-12-31 5953.2
Freq: 10YE-DEC, Name: (United States, Total), dtype: float64As we can see, the US is currently building far fewer homes per decade than was the case 20, 30, 40, and even 50 years ago. This, despite the fact that the country has more than 100 million more residents than was the case in 1970. In other words, there definitely seems to be a serious lack of homes for people to live in. We can see here what we also saw before, that home construction dropped dramatically after the financial crisis of 2008, and hasn't even come close to recovering.
Find, for each decade, the percentage of 1-unit housing starts (of the total) in the overall US. Does the percentage of single-family units appear to be increasing or decreasing over time? Show it in a line plot.
A huge percentage of homes in the US are single-family dwellings. The Census Bureau's data shows not only the total number of homes, but the number of 1-unit homes (as well as a few other numbers of units per building). I was curious to know whether the percentage (not number) of single-family homes had changed over time.
To find this, we'll start with part of the query from the last question, turning the index of years into an index of datetime values:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
)We can then retrieve two parts of the United States column – the part with 1 unit and the part with Total. Once again, we'll use a 2-element tuple:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
[[('United States', '1 unit'), ('United States', 'Total')]]
)We now have two columns, and want to divide the first by the second. We can again use assign to create a new column, pct_1_unit, to get this result. Notice that I need to specify the two columns using the full multi-index name via a tuple; I considered simplifying these, but decided that it wasn't worth the effort for a bit of extra typing:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
[[('United States', '1 unit'), ('United States', 'Total')]]
.resample('10YE').sum()
.assign(pct_1_unit = lambda df_:
df_[('United States', '1 unit')] /
df_[('United States', 'Total')])
)Finally, I selected just the new pct_1_unit column, and created a line plot from it:
(
starts_df
.reset_index()
.assign(date = lambda df_: pd.to_datetime(df_['index'].astype(str) + '-12-31'))
.set_index('date')
[[('United States', '1 unit'), ('United States', 'Total')]]
.resample('10YE').sum()
.assign(pct_1_unit = lambda df_:
df_[('United States', '1 unit')] /
df_[('United States', 'Total')])
['pct_1_unit']
.plot.line()
)The resulting line plot shows the percentage of single-unit homes constructed per decade in the overall United States:

We can see that the proportion of single-family homes dropped from the 1970s to the 1990s, when they took off. But then the percentage dropped again starting in about 2010, leveling off in 2020.
Well... that is true, but it ignores the bigger picture, namely that this seemingly huge changed was really from 80 percent down to 67 percent, and then back to 80 percent again, before coming down to the current 70 percent or so. In other words, even these wild-seeming changes depicted in the plot are only a swing of 10 points or so – not a major change in housing policy over the last few decades.
In which year did we see the most and least 1-unit homes completed, in the US overall and in each of the tracked regions?
For this question, I asked you to look at completed homes, and to find the years in which we had the most and fewest completions.
To answer this, we needed to use a few tools:
- Once again, the
xsmethod, which lets us retrieve matches to a particular value in a multi-index. Here, we specify that we want'1 unit'homes from the columns. - We use the two aggregation methods
idxminandidxmax, which are similar tominandmax, except that these return the index where the min and max were found, rather than the min and max values themselves. - Normally, we can run only a single aggregation method on a data frame. But by using
agg, we can pass a list of strings, each specifying the name of an aggregation method we want to invoke.
The full query is:
(
comps_df
.xs('1 unit', level=1, axis='columns')
.agg(['idxmin', 'idxmax'])
)The result:
Year United States Northeast Midwest South West
idxmin 2011 2011 2011 2011 2011
idxmax 2006 1987 2005 2006 2005We can see that across the board, 2011 had a very low number of completed homes. The max varied a bit more, with 2005 and 2006 accurate for all measures except in the Northeast, where 1987 marked the top.
Calculate the correlation between the total number of housing starts in each of the four regions of the United States. Which regions, if any, are highly correlated with one another?
We can use the corr method on a data frame to find correlations between their values. However, I wasn't interested in looking at all of the possible correlations, just with total numbers in each of the four regions in the United States.
I thus started by again using xs to retrieve only those columns with 'Total' in the inner level of the multi-index.
I then used drop to remove the 'United States' column, keeping only the four regions. I then invoked corr:
(
starts_df
.xs('Total', level=1, axis='columns')
.drop(columns='United States')
.corr()
)I got the following result:
Year Northeast Midwest South West
Year
Northeast 1.000000 0.695068 0.362077 0.569715
Midwest 0.695068 1.000000 0.500834 0.716222
South 0.362077 0.500834 1.000000 0.827323
West 0.569715 0.716222 0.827323 1.000000The result from corr always has the same names on the rows and columns, and a 1.0 result down the diagonal (because every value is 100% positively correlated to itself).
We can see high correlations between the West, Midwest, and South, but a pretty low correlation with the Northeast. This reflects, albeit in a different way, the fact that there are so few housing starts in the Northeast relative to the rest of the country.
That's it for this week! You can get a copy of my Jupyter notebook from here: https://drive.google.com/file/d/14XoJ1QHK1KNQxU8k8vOWm1mUMYzsHbTm/view?usp=sharing
I'll be back next Wednesday with more Pandas puzzles based on current events.
Reuven