1. 学ぶ
  2. /
  3. コース
  4. /
  5. pandas によるデータの結合

Connected

演習

merge_asof() を使ったデータセットの作成

merge_asof() 関数は、開始日と終了日のテーブルを使って別のテーブルにフラグを追加するデータセットを作成する際に役立ちます。ここでは、1980年代の米国の四半期 GDP 値を格納した gdp テーブルと、1980年以降の景気後退の開始日および終了日を記録した recession テーブルが用意されています。merge_asof() を使ってこの2つのテーブルを結合し、各四半期が景気後退期に該当するかどうかを示すステータスフラグを作成しましょう。最後に、結果を棒グラフで確認します。

テーブル gdp と recession はあらかじめ読み込まれています。

指示

100 XP
  • Using merge_asof(), merge gdp and recession on date, with gdp as the left table. Save to the variable gdp_recession.
  • Create a list using a list comprehension and a conditional expression, named is_recession, where for each row if the gdp_recession['econ_status'] value is equal to 'recession' then enter 'r' else 'g'.
  • Using gdp_recession, plot a bar chart of gdp versus date, setting the color argument equal to is_recession.