代码之家  ›  专栏  ›  技术社区  ›  dportman

pyspark-将另一列添加到稀疏向量列

  •  2
  • dportman  · 技术社区  · 8 年前

    我有一个pyspark数据框,其中有一列( features )是一个稀疏的向量。例如:

    +------------------+-----+
    |     features     |label|
    +------------------+-----+
    | (4823,[87],[0.0])|  0.0|
    | (4823,[31],[2.0])|  0.0|
    |(4823,[159],[0.0])|  1.0|
    |  (4823,[1],[7.0])|  0.0|
    |(4823,[15],[27.0])|  0.0|
    +------------------+-----+
    

    我想扩大 特征 列中添加其他功能,例如:

    +-------------------+-----+
    |     features      |label|
    +-------------------+-----+
    | (4824,[87],[0.0]) |  0.0|
    | (4824,[31],[2.0]) |  0.0|
    |(4824,[159],[0.0]) |  1.0|
    |  (4824,[1],[7.0]) |  0.0|
    |(4824,[4824],[7.0])|  0.0|
    +-------------------+-----+
    

    有没有办法不用打开 SparseVector 密集然后用新列重新打包成稀疏?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Shaido MadHadders    8 年前

    将新列添加到现有 SparseVector 使用 VectorAssembler ml库中的转换器。它会自动将列组合成向量( DenseVector Sparsevector公司 取决于哪一个使用的内存最少)。使用 矢量汇编程序 将矢量转换为 Densevector公司 在合并过程中(请参见 source code )中。它可以使用如下:

    df = ...
    
    assembler = VectorAssembler(
        inputCols=["features", "new_col"],
        outputCol="features")
    
    output = assembler.transform(df)
    

    简单地增加 Sparsevector公司 ,无需添加任何新值,只需创建具有更大大小的新向量:

    def add_empty_col_(v):
        return SparseVector(v.size + 1, v.indices, v.values)
    
    add_empty_col = udf(add_empty_col_, VectorUDT())
    df.withColumn("sparse", add_empty_col(col("features"))