PySpark 在数据帧列中插入一个常量 SparseVector



我希望在我的数据帧中插入一个名为 "ref" 的列tfIdfFr该列,其类型为 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'

您知道在数据帧列中插入常量稀疏向量的解决方案吗?

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

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]|
+-------------+

相关内容

  • 没有找到相关文章

最新更新