merge_asof() を使ったデータセットの作成
merge_asof() 関数は、開始日と終了日のテーブルを使って別のテーブルにフラグを追加するデータセットを作成する際に役立ちます。ここでは、1980年代の米国の四半期 GDP 値を格納した gdp テーブルと、1980年以降の景気後退の開始日および終了日を記録した recession テーブルが用意されています。merge_asof() を使ってこの2つのテーブルを結合し、各四半期が景気後退期に該当するかどうかを示すステータスフラグを作成しましょう。最後に、結果を棒グラフで確認します。
テーブル gdp と recession はあらかじめ読み込まれています。
この演習はコースの一部です
pandas によるデータの結合
演習の手順
- 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.
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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()