Apache Spark:迭代数据帧行并通过MutableList(Scala)创建新的数据帧

问题描述 投票:0回答:1

我目前正在尝试学习使用Scala中的Apache Spark。

我有下表作为我想用于分析的数据帧

enter image description here

现在我想遍历行,获取body列中字符串的id和字数,并在具有2列的数据帧中输出信息。

def analyseDF(df:DataFrame): Unit = {
      //var retFrame = spark.emptyDataset[ClassIdCount].toDF()
      var tList = mutable.MutableList[IdCount]()

      df.foreach(row => {
        val wordCnt = row.getString(5).split(" ").size
        val mailid = row.getString(0)

        val record = IdCount(mailid.toString(), wordCnt.toInt)
        tList += record

        println(tList)
        println(record)

      })
      tList.toDF().show()
     // tList.toDS().show()

    }

不知何故,在调用tList.toDF()。show()时,具有2列的帧始终为空,但是循环中的记录是正确生成的。有谁能在这里给我一个提示?

scala apache-spark
1个回答
2
投票

典型的初学者错误:tList只存在于驱动程序上,它无法从执行程序端代码更新。这不是您如何从现有数据框创建数据框。改为使用转换/聚合。

在你的情况下,你可以使用内置的Dataframe API函数splitsize来实现:

import org.apache.spark.sql.functions._

val transformedDf = df
  .select(
      $"id",
      size(split($"body"," "))).as("cnt")
  )
© www.soinside.com 2019 - 2024. All rights reserved.