简体   繁体   English

在pyspark SQL DataFrame中乘以稀疏向量的行

[英]Multiplying rows of Sparse vectors in pyspark SQL DataFrame

I'm having difficulties multiplying elements of columns in a SQL data frame. 我在将SQL数据框中的列元素相乘时遇到困难。

sv1 = Vectors.sparse(3, [0, 2], [1.0, 3.0])
sv2 = Vectors.sparse(3, [0, 1], [2.0, 4.0])

def xByY(x,y):
  return np.multiply(x,y)

print(xByY(sv1, sv2))

The above works. 以上作品。

But the below doesn't. 但是下面没有。

xByY_udf = udf(xByY)

tempDF = sqlContext.createDataFrame([(sv1, sv2), (sv1, sv2)], ('v1', 'v2'))
tempDF.show()

print(tempDF.select(xByY_udf('v1', 'v2')).show())

Many thanks! 非常感谢!

If you want your udf to return a SparseVector , we'll first need to modify the output of your function, and secondly set the output schema of the udf to VectorUDT() : 如果你希望你的udf返回一个SparseVector ,我们首先需要修改你的函数的输出,其次设定的输出模式udfVectorUDT()

To declare a SparseVector , we need the size of the original array, and both the indices and the values of the non-zero elements. 要声明SparseVector ,我们需要原始数组的大小 ,以及索引非零元素的 We can find these using len() and list comprehensions if the intermediate result of the multiplication is a list : 如果乘法的中间结果是一个list我们可以使用len()和list comprehensions找到它们:

from pyspark.ml.linalg import Vectors, VectorUDT

def xByY(x,y):
  res = np.multiply(x,y).tolist()
  vec_args =  len(res), [i for i,x in enumerate(res) if x != 0], [x for x in res if x != 0] 
  return Vectors.sparse(*vec_args)  

Now we can declare our udf and test it: 现在我们可以声明我们的udf并对其进行测试:

xByY_udf = udf(xByY, VectorUDT())
tempDF.select(xByY_udf('v1', 'v2')).show()
+-------------+
| xByY(v1, v2)|
+-------------+
|(3,[0],[2.0])|
|(3,[0],[2.0])|
+-------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM