Spark SQL 将数据集转换为数据框架。

10

如何将数据集对象转换为数据帧?在我的示例中,我正在将JSON文件转换为数据帧,并将其转换为数据集。在数据集中,我添加了一些额外的属性(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"
  }

我期望在 s.printschema() 的输出结果中添加一个名为 newColumn 的新列名,但实际上没有出现。这是为什么?有什么原因吗?我该如何实现呢?

1个回答

8
Product Encoder 的输出架构完全基于其构造函数签名的确定。因此,发生在构造函数体内的任何内容都将被简单地丢弃。
您可以...
empData.map(x => (x, x.newColumn)).toDF("value", "newColumn")

3
谢谢。最终代码部分如下:val r = res.map(s => (s.name,s.gender,s.company,s.address,s.newColumn)).toDF("name", "gender", "company", "address", "newColumn");有没有一种快捷的方法来传递参数给 toDF 函数?如果类有更多的参数,提供所有值可能会很困难。是否有任何快捷方式? - Learn Hadoop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接