開始使用免費開始

為向量資料建立 UDF

有一個名為 df 的 DataFrame,其中包含型別為 vector 的欄位 output。主控台已顯示其前 5 列。

本練習屬於課程

Python Spark SQL 入門

檢視課程

練習說明

  • 建立名為 first_udf 的 UDF,用來選取向量欄位的第一個元素。對於不是包含至少一個項目的向量的資料,將結果設為預設值 0.0,並將輸出轉型為 float。
  • df 使用 select 操作,將 first_udf 套用到 output 欄位。

動手互動練習

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

# Selects the first element of a vector column
first_udf = ____(lambda x:
            ____(x.indices[0]) 
            if (x and hasattr(x, "toArray") and x.____())
            else 0.0,
            FloatType())

# Apply first_udf to the output column
df.select(____("output").alias("result")).show(5)
編輯並執行程式碼