用 SQL 查詢篩選資料表
在前一個練習中,你已經在 DataFrame 上執行過一個簡單的 SQL 查詢。你也可以撰寫更進階的查詢,來取得所需結果,並用於後續的分析,例如資料視覺化與機器學習。本練習會使用你之前建立的暫存資料表 people,將「sex」為 male 與 female 的列分別篩選出來,並建立兩個 DataFrame。
請注意,這題的「解答」對 SQL 指令的大小寫敏感(例如,只接受 FROM,不接受 from)。而且「解答」只接受「==」,不接受「=`」。
提醒你,工作區中已提供 SparkSession spark,以及暫存資料表 people。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 將
people資料表中 sex 為 female 的所有列篩選出來,存成people_female_dfDataFrame。 - 將
people資料表中 sex 為 male 的所有列篩選出來,存成people_male_dfDataFrame。 - 分別計算
people_female與people_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.____()))