如何从 PySpark 中的向量列中提取浮点数?

How to extract floats from vector columns in PySpark?

我的 Spark DataFrame 具有以下格式的数据:

printSchema()表示每一列都是vector类型。

我尝试使用下面的代码(对于 1 列 col1)从 [] 中获取值:

from pyspark.sql.functions import udf
from pyspark.sql.types import FloatType

firstelement=udf(lambda v:float(v[0]),FloatType())
df.select(firstelement('col1')).show()

但是,如何将它应用到 df 的所有列?

据我了解您的问题,您不需要使用 UDF 将 Vector 更改为普通的 Float 类型。使用pyspark预定义函数concat_ws

>>> from pyspark.sql.functions import *
>>> df.show()
+------+
|   num|
+------+
| [211]|
|[3412]|
| [121]|
| [121]|
|  [34]|
|[1441]|
+------+

>>> df.printSchema()
root
 |-- num: array (nullable = true)
 |    |-- element: string (containsNull = true)

>>> df.withColumn("num", concat_ws("", col("num"))).show()
+----+
| num|
+----+
| 211|
|3412|
| 121|
| 121|
|  34|
|1441|
+----+

1。提取单个向量列的第一个元素:

要获取向量列的第一个元素,您可以使用此 SO 中的答案:讨论 Access element of a vector in a Spark DataFrame (Logistic Regression probability vector)

这是一个可重现的例子:

>>> from pyspark.sql import functions as f
>>> from pyspark.sql.types import FloatType
>>> df = spark.createDataFrame([{"col1": [0.2], "col2": [0.25]},
                                {"col1": [0.45], "col2":[0.85]}])
>>> df.show()
+------+------+
|  col1|  col2|
+------+------+
| [0.2]|[0.25]|
|[0.45]|[0.85]|
+------+------+

>>> firstelement=f.udf(lambda v:float(v[0]),FloatType())
>>> df.withColumn("col1", firstelement("col1")).show()
+----+------+
|col1|  col2|
+----+------+
| 0.2|[0.25]|
|0.45|[0.85]|
+----+------+

2。提取多个向量列的第一个元素:

要将上述解决方案推广到多列,请应用 for loop。这是一个例子:

>>> from pyspark.sql import functions as f
>>> from pyspark.sql.types import FloatType

>>> df = spark.createDataFrame([{"col1": [0.2], "col2": [0.25]},
                                {"col1": [0.45], "col2":[0.85]}])
>>> df.show()
+------+------+
|  col1|  col2|
+------+------+
| [0.2]|[0.25]|
|[0.45]|[0.85]|
+------+------+

>>> firstelement=f.udf(lambda v:float(v[0]),FloatType())
>>> df = df.select([firstelement(c).alias(c) for c in df.columns])
>>> df.show()
+----+----+
|col1|col2|
+----+----+
| 0.2|0.25|
|0.45|0.85|
+----+----+