開始使用免費開始

在 RDD 中做彙總

既然你已經用 PySpark 的 DataFrame 做過分析,我們也用 RDD 快速做一次類似的任務。請使用提供的程式碼,在 PySpark 中計算一個 RDD 的數值總和。

已為你建立名為 spark 的 Spark 工作階段。

本練習屬於課程

PySpark 入門

檢視課程

練習說明

  • 由提供的 DataFrame 建立一個 RDD。
  • 對 RDD 的鍵套用提供的 Lambda 函式。
  • 收集並檢視彙總結果。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# DataFrame Creation
data = [("HR", "3000"), ("IT", "4000"), ("Finance", "3500")]
columns = ["Department", "Salary"]
df = spark.createDataFrame(data, schema=columns)

# Map the DataFrame to an RDD
rdd = df.rdd.____(lambda row: (row["Department"], row["Salary"]))

# Apply a lambda function to get the sum of the DataFrame
rdd_aggregated = rdd.____(lambda x, y: x + y)

# Show the collected Results
print(rdd_aggregated.____())
編輯並執行程式碼