scala - Spark SQL 将数据集转换为数据框
问题描述
如何将数据集 obj 转换为数据框?在我的示例中,我将 JSON 文件转换为数据帧并转换为 DataSet。在数据集中,我添加了一些额外的属性(newColumn
)并将其转换回数据框。这是我的示例代码:
val empData = sparkSession.read.option("header", "true").option("inferSchema", "true").option("multiline", "true").json(filePath)
......
import sparkSession.implicits._
val res = empData.as[Emp]
//for (i <- res.take(4)) println(i.name + " ->" + i.newColumn)
val s = res.toDF();
s.printSchema()
}
case class Emp(name: String, gender: String, company: String, address: String) {
val newColumn = if (gender == "male") "Not-allowed" else "Allowed"
}
但我预计newColumn
在s.printschema()
. 输出结果。但它没有发生吗?为什么?任何原因?我怎样才能做到这一点?
解决方案
输出的模式Product
Encoder
完全取决于它的构造函数签名。因此,身体中发生的任何事情都被简单地丢弃。
你可以
empData.map(x => (x, x.newColumn)).toDF("value", "newColumn")
推荐阅读
- highcharts - 以柱状图而不是饼图显示向下钻取
- powershell - 如何让 Octopus 在 NuGet 包的内容文件夹中执行 ps1 脚本?
- angular - 调试类型脚本停止在 Visual Studio 代码中工作
- python - 如何在python中将数字转换为base 64?
- svelte - 调试 Sapper 服务器端
- powershell - Powershell - 根据第二个文件数据从文件中提取数据
- python - 尝试在默认 VPC 之外使用 Apache libcloud 部署 ec2 实例
- arrays - 基于关键字搜索字符串(不能比较多个关键字)VB.NET
- extjs - Extjs TreeStore,多个异步请求,treepanel渲染错位
- r - 为什么 R 中的 rle 返回不正确的长度?