【问题标题】:Mapping and removing duplicates in Spark Scala?在 Spark Scala 中映射和删除重复项?
【发布时间】:2018-04-25 19:41:27
【问题描述】:

我有一个数据集test.txt。它包含如下数据

1::1::3
1::1::2
1::2::2
2::1::5
2::1::4
2::2::2
3::1::1
3::2::2

我使用以下代码创建了数据框。

case class Rating(userId: Int, movieId: Int, rating: Float)
def parseRating(str: String): Rating = {
val fields = str.split("::")
assert(fields.size == 3)
Rating(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/cravi/Desktop/test.txt").map(parseRating).toDF()

但是当我尝试打印输出时,我得到的输出低于输出

[1,1,3.0]
[1,1,2.0]
[1,2,2.0]
[2,1,2.0]
[2,1,4.0]
[2,2,2.0]
[3,1,1.0]
[3,2,2.0]

但我想打印如下所示的输出,即删除重复的组合,而不是 field(2) value 1.0。

[1,1,1.0]
[1,2,1.0]
[2,1,1.0]
[2,2,1.0]
[3,1,1.0]
[3,2,1.0]

【问题讨论】:

    标签: scala apache-spark apache-spark-sql scala-collections


    【解决方案1】:

    创建dataframe 后,可以通过调用.dropDuplicates(columnNames) 来删除重复项,并可以使用lit 和withColumn 函数来使用1.0 填充第三列。

    总结起来,简单的解决方法如下

    val ratings = sc.textFile("C:/Users/cravi/Desktop/test.txt")
        .map(line => line.split("::"))
        .filter(fields => fields.length == 3)
        .map(fields => Rating(fields(0).toInt, fields(1).toInt, 1.0f))
      .toDF().dropDuplicates("userId", "movieId")
    
    ratings.show(false)
    

    这应该给你

    +------+-------+------+
    |userId|movieId|rating|
    +------+-------+------+
    |3     |1      |1.0   |
    |2     |2      |1.0   |
    |1     |2      |1.0   |
    |1     |1      |1.0   |
    |2     |1      |1.0   |
    |3     |2      |1.0   |
    +------+-------+------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 2019-03-08
      相关资源
      最近更新 更多