开始使用免费开始使用

为向量数据创建 UDF

已提供数据框 df,其中包含一个类型为 vector 的列 output。其前 5 行已在控制台显示。

本练习是课程的一部分

Python 中的 Spark SQL 入门

查看课程

练习说明

  • 创建名为 first_udf 的 UDF。它选择向量列的第一个元素。对于不是向量或不包含至少 1 个元素的项,结果设为默认值 0.0,并将输出转换为浮点数。
  • 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)
编辑并运行代码