PySpark在Dataframe列中插入常量SparseVector

时间:2019-01-15 10:18:36

标签: python apache-spark pyspark apache-spark-sql apache-spark-ml

我希望在数据框tfIdfFr中插入名为"ref"的列,该列的类型为pyspark.ml.linalg.SparseVector

当我尝试这个

ref = tfidfTest.select("features").collect()[0].features # the reference
tfIdfFr.withColumn("ref", ref).select("ref", "features").show()

我收到此错误AssertionError: col should be Column

当我尝试这个时:

from pyspark.sql.functions import lit
tfIdfFr.withColumn("ref", lit(ref)).select("ref", "features").show()

我收到错误消息AttributeError: 'SparseVector' object has no attribute '_get_object_id'

您知道在Dataframe列中插入常量SparseVector的解决方案吗?*

1 个答案:

答案 0 :(得分:1)

在这种情况下,我将跳过收集:

ref = tfidfTest.select(col("features").alias("ref")).limit(1)
tfIdfFr.crossJoin(ref)

通常,您可以使用udf

from pyspark.ml.linalg import DenseVector, SparseVector, Vector, Vectors, \
 VectorUDT 
from pyspark.sql.functions import udf

def vector_lit(v): 
    assert isinstance(v, Vector) 
    return udf(lambda: v, VectorUDT())() 

用法:

spark.range(1).select(
  vector_lit(Vectors.sparse(5, [1, 3], [-1, 1])
).alias("ref")).show()
+--------------------+
|                 ref|
+--------------------+
|(5,[1,3],[-1.0,1.0])|
+--------------------+
spark.range(1).select(vector_lit(Vectors.dense([1, 2, 3])).alias("ref")).show() 
+-------------+
|          ref|
+-------------+
|[1.0,2.0,3.0]|
+-------------+

也可以使用中间表示形式:

import json
from pyspark.sql.functions import from_json, lit
from pyspark.sql.types import StructType, StructField

def as_column(v):
    assert isinstance(v, Vector) 
    if isinstance(v, DenseVector):
        j = lit(json.dumps({"v": {
          "type": 1,
          "values": v.values.tolist()
        }}))
    else:
        j = lit(json.dumps({"v": {
          "type": 0,
          "size": v.size,
          "indices": v.indices.tolist(),
          "values": v.values.tolist()
        }}))
    return from_json(j, StructType([StructField("v", VectorUDT())]))["v"]

用法:

spark.range(1).select(
    as_column(Vectors.sparse(5, [1, 3], [-1, 1])
 ).alias("ref")).show()  
+--------------------+
|                 ref|
+--------------------+
|(5,[1,3],[-1.0,1.0])|
+--------------------+
spark.range(1).select(as_column(Vectors.dense([1, 2, 3])).alias("ref")).show()
+-------------+
|          ref|
+-------------+
|[1.0,2.0,3.0]|
+-------------+