始める無料で始める

DataFrame をフィルタリングする

前の演習では、主に列方向の抽出に使う select() 演算子でデータをサブセット化しました。では、条件に基づいて DataFrame をサブセット化したい場合(例:性別が Female のすべての行を選択)にはどうすればよいでしょうか。この演習では、people_df DataFrame の中から 'sex' が female と male の行をそれぞれフィルタリングして、2つの異なるデータセットを作成します。最後に、それぞれのデータセットの行数を数えます。

ワークスペースにはすでに SparkSession spark と DataFrame people_df が用意されています。

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

PySparkで学ぶBig Data入門

コースを見る

演習の手順

  • people_df DataFrame をフィルタリングし、sex が female のすべての行を選択して people_df_female DataFrame を作成します。
  • people_df DataFrame をフィルタリングし、sex が male のすべての行を選択して people_df_male DataFrame を作成します。
  • people_df_femalepeople_df_male の各 DataFrame の行数をカウントします。

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

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

# Filter people_df to select females 
people_df_female = people_df.____(people_df.____ == "female")

# Filter people_df to select males
people_df_male = people_df.____(____ == "____")

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