向量列到doubleTyp的Pyspark转换

2024-09-24 00:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有向量类型的列,每个向量中有一个值。我只想得到那个值并保持列为doubleType。你知道吗

输入df示例:

|testcol|
[1.3]|
[1.2]|
[3.4]|

期望输出df:

|testcol|
|1.3|
|1.2|
|3.4|

到目前为止我掌握的代码:

remove_vector_func = udf(lambda x: list(x)[0], DoubleType())
ex= ex.withColumn("testcol", remove_vector_func("testcol"))

此代码运行,但当我尝试显示列时,它会不断抛出错误:

expected zero arguments for construction of ClassDict (for numpy.dtype)

我在printSchema()中看到列类型是正确的:

testcol: double (nullable = true)

Tags: lambda代码示例类型dffor向量remove
1条回答
网友
1楼 · 发布于 2024-09-24 00:32:08

您只需要确保lambda函数返回与UDF的返回类型匹配的对象。在这种情况下,需要将对象转换为float类型

代码:

from pyspark.ml.linalg import Vectors
from pyspark.sql.functions import udf
from pyspark.sql.types import DoubleType

ex = spark.createDataFrame([[1.3],
                            [1.2],
                            [3.4]
                           ], ["test"])

from pyspark.ml.feature import VectorAssembler
assembler = VectorAssembler(inputCols=["test"],outputCol="testcol")
ex = assembler.transform(ex)
ex.show(5)

# UDF for converting column type from vector to double type
unlist = udf(lambda x: float(list(x)[0]), DoubleType())

ex = ex.withColumn("testcol_new", unlist("testcol"))
ex.show(5)

输出:

output

相关问题 更多 >