我有这样的数据框:
+------+-----+-------------------+--------------------+
| Id|Label| Timestamp| Signal_list|
+------+-----+-------------------+--------------------+
|A05439| 1|2014-05-20 05:05:21|[-116, -123, -129...|
|A06392| 1|2013-12-27 04:12:33|[260, 314, 370, 4...|
|A08192| 1|2014-06-03 04:06:15|[334, 465, 628, 8...|
|A08219| 3|2013-12-31 03:12:41|[-114, -140, -157...|
|A02894| 2|2013-10-28 06:10:53|[109, 139, 170, 1...|
这个数据帧信号列表有9k个元素,我想把信号列表列转换成vector。我尝试了下面的UDF:
import org.apache.spark.ml.linalg._
val convertUDF = udf((array : Seq[Long]) => {
Vectors.dense(array.toArray)
})
val afWithVector = afLabel.select("*").withColumn("Signal_list", convertUDF($"Signal_list"))
但它给出了错误:
console>:39: error: overloaded method value dense with alternatives:
(values: Array[Double])org.apache.spark.ml.linalg.Vector <and>
(firstValue: Double,otherValues: Double*)org.apache.spark.ml.linalg.Vector
cannot be applied to (Array[Long])
Vectors.dense(array.toArray)
Dataframe架构:
|-- Id: string (nullable = true)
|-- Label: integer (nullable = true)
|-- Timestamp: string (nullable = true)
|-- Signal_list: array (nullable = true)
| |-- element: long (containsNull = true)
我是使用scala的新手,使用pyspark的答案会更有帮助。
答案 0 :(得分:1)
UDF
几乎是正确的。问题在于Spark中的向量只能使用双精度数,不接受长数。 Scala中的变化看起来像这样:
val convertUDF = udf((array : Seq[Long]) => {
Vectors.dense(array.toArray.map(_.toDouble))
})
在Python中我相信它会是这样的:
udf(lambda vs: Vectors.dense([float(i) for i in vs]), VectorUDT())