開始使用免費開始

Split 與 Explode

把像 GARAGEDESCRIPTION 這樣的複合欄位轉換成有用的資訊,往往需要多個步驟。及早釐清展開後能帶來的價值會很有幫助。在這個例子中,我們會先把字串轉成類似清單的陣列,接著將其展開(explode),然後再檢視其中的唯一值。

本練習屬於課程

使用 PySpark 進行特徵工程

檢視課程

練習說明

  • pyspark.sql.functions 匯入需要的函式 split()explode()
  • 使用 split() 以 ', '(逗號加空格)分割 df['GARAGEDESCRIPTION'],建立新欄位 garage_list
  • 使用 explode()df['garage_list'] 中的每個值各建立一筆新紀錄,並指定到新欄位 ex_garage_list
  • 使用 distinct() 取得 ex_garage_list 的唯一值,並以 show 顯示前 100 列,為了呈現方便將其截斷為 50 個字元。

動手互動練習

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

# Import needed functions
____ ____ ____ ____, ____

# Convert string to list-like array
df = df.withColumn(____, ____(____, ____))

# Explode the values into new records
ex_df = df.withColumn(____, ____(____))

# Inspect the values
ex_df[['ex_garage_list']].____().____(100, ____=____)
編輯並執行程式碼