始める無料で始める

テーブルをフィルタリングするSQLクエリ

前の演習では、DataFrameに対してシンプルなSQLクエリを実行しました。可視化やMachine Learningなどの後続の分析に使えるように、より高度なクエリを作成して、必要な結果を得ることもできます。この演習では、先ほど作成した一時テーブル people を使い、"sex" が male と female の行をそれぞれ抽出して、2つのDataFrameを作成します。

なお、「解答」はSQLコマンドの大文字・小文字を区別します(たとえば FROM は受け付けますが from は不可)。また、「解答」では == のみを受け付け、= は不可です。

ワークスペースにはすでに SparkSession spark と一時テーブル people が用意されています。

この演習はコースの一部です

PySparkで学ぶBig Data入門

コースを見る

演習の手順

  • people テーブルをフィルタリングし、sex が female のすべての行を people_female_df DataFrame に取得します。
  • people テーブルをフィルタリングし、sex が male のすべての行を people_male_df DataFrame に取得します。
  • people_femalepeople_male の両方のDataFrameで、行数をカウントします。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Filter the people table to select female sex 
people_female_df = spark.____('SELECT * FROM ____ WHERE sex=="____"')

# Filter the people table DataFrame to select male sex
people_male_df = spark.____('SELECT * ____ people ____ ____=="____"')

# Count the number of rows in both people_df_female and people_male_df DataFrames
print("There are {} rows in the people_female_df and {} rows in the people_male_df DataFrames".format(people_female_df.____(), people_male_df.____()))
コードを編集して実行