将新列添加到现有
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"))