[英]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
,我们首先需要修改你的函数的输出,其次设定的输出模式udf
到VectorUDT()
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.