如何将Vector分割成列 – 使用PySpark

上下文:我有一个DataFrame 2列:单词和vector。 其中“向量”的列types是VectorUDT

一个例子:

 word | vector assert | [435,323,324,212...] 

我想得到这个:

 word | v1 | v2 | v3 | v4 | v5 | v6 ...... assert | 435 | 5435| 698| 356|.... 

题:

如何使用pyspark为每个维度在多个列中使用向量分隔列?

提前致谢

一种可能的方法是转换RDD:

 from pyspark.ml.linalg import Vectors df = sc.parallelize([ ("assert", Vectors.dense([1, 2, 3])), ("require", Vectors.sparse(3, {1: 2})) ]).toDF(["word", "vector"]) def extract(row): return (row.word, ) + tuple(row.vector.toArray().tolist()) df.rdd.map(extract).toDF(["word"]) # Vector values will be named _2, _3, ... ## +-------+---+---+---+ ## | word| _2| _3| _4| ## +-------+---+---+---+ ## | assert|1.0|2.0|3.0| ## |require|0.0|2.0|0.0| ## +-------+---+---+---+ 

另一种解决scheme是创build一个UDF:

 from pyspark.sql.functions import udf, col from pyspark.sql.types import ArrayType, DoubleType def to_array(col): def to_array_(v): return v.toArray().tolist() return udf(to_array_, ArrayType(DoubleType()))(col) (df .withColumn("xs", to_array(col("vector"))) .select(["word"] + [col("xs")[i] for i in range(3)])) ## +-------+-----+-----+-----+ ## | word|xs[0]|xs[1]|xs[2]| ## +-------+-----+-----+-----+ ## | assert| 1.0| 2.0| 3.0| ## |require| 0.0| 2.0| 0.0| ## +-------+-----+-----+-----+