Using merge_asof() to create dataset
The merge_asof() function can be used to create datasets where you have a table of start and stop dates, and you want to use them to create a flag in another table. You have been given gdp, which is a table of quarterly GDP values of the US during the 1980s. Additionally, the table recession has been given to you. It holds the starting date of every US recession since 1980, and the date when the recession was declared to be over. Use merge_asof() to merge the tables and create a status flag if a quarter was during a recession. Finally, to check your work, plot the data in a bar chart.
The tables gdp and recession have been loaded for you.
This exercise is part of the course
Joining Data with pandas
Exercise instructions
- Using merge_asof(), mergegdpandrecessionondate, withgdpas the left table. Save to the variablegdp_recession.
- Create a listusing a list comprehension and a conditional expression, namedis_recession, where for each row if thegdp_recession['econ_status']value is equal to 'recession' then enter'r'else'g'.
- Using gdp_recession, plot a bar chart ofgdpversusdate, setting thecolorargument equal tois_recession.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Merge gdp and recession on date using merge_asof()
gdp_recession = ____
# Create a list based on the row value of gdp_recession['econ_status']
is_recession = ['____' if s=='recession' else '____' for s in gdp_recession['econ_status']]
# Plot a bar chart of gdp_recession
gdp_recession.plot(kind=____, y=____, x=____, color=____, rot=90)
plt.show()