scala - Spark Scala 总结数据集的列元素?

标签 scala count apache-spark

我需要计算每列中出现值示例“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/

相关文章:

scala - com.typesafe.config.ConfigException$NotResolved : has not been resolved,

apache-spark - 谷歌云 dataproc --files 不起作用

hadoop - 当应用程序 jar 在 hdfs 中时,Spark-submit 不起作用

Scala val 和 var 相关问题和 Scala 要求我在声明时分配一个值

scala - 面向 future 的 Scala/SBT 项目

scala - 隐式转换怪异

mysql - 从两个具有不同列的表中进行选择,其中一个需要计数

mysql - 计算引用同一表中主键的外键的出现次数

mysql - 卡住了 mysql join with count 查询

python-3.x - 在同一个 jvm 中同时运行多个 Spark 实例的最佳实践?