Using .melt() for stocks vs bond performance
It is widespread knowledge that the price of bonds is inversely related to the price of stocks. In this last exercise, you'll review many of the topics in this chapter to confirm this. You have been given a table of percent change of the US 10-year treasury bond price. It is in a wide format where there is a separate column for each year. You will need to use the .melt()
method to reshape this table.
Additionally, you will use the .query()
method to filter out unneeded data. You will merge this table with a table of the percent change of the Dow Jones Industrial stock index price. Finally, you will plot data.
The tables ten_yr
and dji
have been loaded for you.
This exercise is part of the course
Joining Data with pandas
Exercise instructions
- Use
.melt()
onten_yr
to unpivot everything except themetric
column, settingvar_name='date'
andvalue_name='close'
. Save the result tobond_perc
. - Using the
.query()
method, select only those rows wheremetric
equalsclose
, and save tobond_perc_close
. - Use
merge_ordered()
to mergedji
(left table) andbond_perc_close
ondate
with an inner join, and setsuffixes
equal to('_dow', '_bond')
. Save the result todow_bond
. - Using
dow_bond
, plot only the Dow and bond values.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Use melt on ten_yr, unpivot everything besides the metric column
bond_perc = ____
# Use query on bond_perc to select only the rows where metric=close
bond_perc_close = ____
# Merge (ordered) dji and bond_perc_close on date with an inner join
dow_bond = ____
# Plot only the close_dow and close_bond columns
dow_bond.plot(____, x='date', rot=90)
plt.show()