我目前正在尝试学习使用Scala中的Apache Spark。
我有下表作为我想用于分析的数据帧
现在我想遍历行,获取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列的帧始终为空,但是循环中的记录是正确生成的。有谁能在这里给我一个提示?
典型的初学者错误:tList
只存在于驱动程序上,它无法从执行程序端代码更新。这不是您如何从现有数据框创建数据框。改为使用转换/聚合。
在你的情况下,你可以使用内置的Dataframe API函数split
和size
来实现:
import org.apache.spark.sql.functions._
val transformedDf = df
.select(
$"id",
size(split($"body"," "))).as("cnt")
)