【问题标题】:Grouping duplicates in a csv file在 csv 文件中对重复项进行分组
【发布时间】:2020-11-29 10:16:51
【问题描述】:

我有一个 CSV 文件,我已将案例类应用到该文件上并制作成一个列表,例如

CSV 文件是这样的 -

"user_id","age","liked_ad","location"
2145,34,true,USA
6786,25,true,UK
9025,21,false,USA
1145,40,false,UK

它继续。最终,我试图找到拥有最喜欢的广告(真实值)的顶级 user_id。我知道 csv 文件中存在重复项 -

val origFile = processCSV("src/main/resources/advert-data.csv")
val origFileLength = origFile.length

val uniqueList = origFile.distinct
val uniqueListLength = uniqueList.length

两个长度不同。我想我需要对所有 user_id 进行分组,以便相同 user_id 的所有条目都在一个组中,然后我可以计算该用户条目中有多少“真”。我完全被困在正确的方法上。

这是我此刻的 processCSV 函数 -

final case class AdvertInfo(userId: Int, age: Int, likedAd: Boolean, location: String)

    def processCSV(file: String): List[AdvertInfo] = {
      val data = io.Source.fromFile(file)

      data
        .getLines()
        .map(_.split(',').iterator.map(_.trim).toList)
        .flatMap {
          case userIdRaw :: ageRaw :: likedAdRaw :: locationRaw :: Nil =>
            for {
              userId <- userIdRaw.toIntOption
              age <- ageRaw.toIntOption
              likedAd <- likedAdRaw.toBooleanOption
              location <- Some(locationRaw)
            } yield AdvertInfo(userId, age, likedAd, location)
          case _ =>
            None
        }.toList
    }

【问题讨论】:

    标签: scala csv


    【解决方案1】:

    您的描述有点混乱,但我认为您想要的是:

    origFile.filter(_.likedAd)
            .groupMapReduce(_.userId)(_ => 1)(_+_) //Scala 2.13.x
    

    结果是Map,其中user_ids 作为键,所有liked_ad=="true" 的计数作为值。

    您可以从那里.toList.sortBy(-_._2) 以获得按赞数排名。

    【讨论】:

    • 嗨,当我尝试过滤 origFile 时,我得到“无法解析重载方法”
    • @monkeys73;如果origFileList[AdvertInfo] 类型(这是processCSV() supposed 要返回的),那么我认为编译器没有理由感到困惑。 filter() 电话对我有用,就像描述的那样。
    猜你喜欢
    • 2021-12-23
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多