我需要计算每列中出现值示例“2”的次数。
我的数据集具有以下结构:
1 1 2 0 0 0 2
0 2 0 1 1 1 1
1 2 1 0 2 2 2
0 0 0 0 1 1 2
我导入了文件:
val ip = sc.textFile("/home/../data-scala.txt").map(line => line.split(" "))
如何对每列中等于“2”的值求和?我希望得到一个元素数组作为结果
[0,2,1,0,1,1,3]
最佳答案
像这样怎么样:
import breeze.linalg.DenseVector
def toInd(s: String): DenseVector[Int] = {
DenseVector[Int](s.split(" ").map(x => if(x == "2") 1 else 0))
}
sc.textFile("/path/to/file").map(toInd).reduce(_ + _)
如果您期望总和为零的大量列,可以将 DenseVector
替换为 SparseVector
。
上述解决方案需要为 RDD 的每个元素一个新的 DenseVector
对象。出于性能原因,您可以考虑使用聚合
和向量突变:
def seqOp(acc: DenseVector[Int] , cols: Array[String]): DenseVector[Int] = {
cols.zipWithIndex.foreach{ case (x, i) => if(x == "2") acc(i) += 1}
acc
}
def combOp(acc1: DenseVector[Int], acc2: DenseVector[Int]): DenseVector[Int] = {
acc1 += acc2
acc1
}
val n = ip.first.length
ip.aggregate(DenseVector.zeros[Int](n))(seqOp, combOp)
如果需要,您可以轻松地将 DenseVector
替换为稀疏向量或 scala.collection.mutable.Map
。
如果你问我,它相当难看,所以我提供它只是为了使答案完整。
关于scala - Spark Scala 总结数据集的列元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31610074/