分組與彙總 II
除了你已經看過的 GroupedData 方法之外,還有 .agg() 方法。
這個方法能讓你傳入彙總欄位運算式,使用 pyspark.sql.functions 子模組中的任一彙總函式。
這個子模組包含許多實用函式,可用來計算標準差等統計量。此子模組裡的所有彙總函式,都會接收 GroupedData 資料表中的欄位名稱。
請記得,名為 spark 的 SparkSession 已在你的工作區中,還有 Spark DataFrame flights。你在上一題建立的分組 DataFrame 也都在工作區中。
本練習屬於課程
PySpark 基礎
練習說明
- 匯入子模組
pyspark.sql.functions並命名為F。 - 建立名為
by_month_dest的GroupedData資料表,依month與dest兩個欄位分組。請將兩個欄位名稱分別以字串作為獨立引數傳入。 - 在
by_month_destDataFrame 上使用.avg()方法,取得每個目的地在各個月份的dep_delay平均值。 - 使用
.agg()方法搭配函式F.stddev(),計算dep_delay的標準差。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import pyspark.sql.functions as F
import ____ as F
# Group by month and dest
by_month_dest = flights.groupBy(____)
# Average departure delay by month and destination
by_month_dest.____.show()
# Standard deviation of departure delay
by_month_dest.agg(F.____(____)).show()