DataFrame をフィルタリングする
前の演習では、主に列方向の抽出に使う select() 演算子でデータをサブセット化しました。では、条件に基づいて DataFrame をサブセット化したい場合(例:性別が Female のすべての行を選択)にはどうすればよいでしょうか。この演習では、people_df DataFrame の中から 'sex' が female と male の行をそれぞれフィルタリングして、2つの異なるデータセットを作成します。最後に、それぞれのデータセットの行数を数えます。
ワークスペースにはすでに SparkSession spark と DataFrame people_df が用意されています。
この演習はコースの一部です
PySparkで学ぶBig Data入門
演習の手順
people_dfDataFrame をフィルタリングし、sex が female のすべての行を選択してpeople_df_femaleDataFrame を作成します。people_dfDataFrame をフィルタリングし、sex が male のすべての行を選択してpeople_df_maleDataFrame を作成します。people_df_femaleとpeople_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.____()))