加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 尝试将数据帧行映射到更新行时的编码器错误

发布时间:2020-12-16 19:02:49 所属栏目:安全 来源:网络整理
导读:当我试图在我的代码中做同样的事情,如下所述 dataframe.map(row = { val row1 = row.getAs[String](1) val make = if (row1.toLowerCase == "tesla") "S" else row1 Row(row(0),make,row(2))}) 我从这里得到以上参考: Scala: How can I replace value in Da
当我试图在我的代码中做同样的事情,如下所述

dataframe.map(row => {
  val row1 = row.getAs[String](1)
  val make = if (row1.toLowerCase == "tesla") "S" else row1
  Row(row(0),make,row(2))
})

我从这里得到以上参考:
Scala: How can I replace value in Dataframs using scala
但是我正在得到编码器错误

Unable to find encoder for type stored in a Dataset. Primitive types
(Int,S tring,etc) and Product types (case classes) are supported by
importing spark.im plicits._ Support for serializing other types will
be added in future releases.

注意:我正在使用火花2.0!

解决方法

这里没有什么意想不到的您正在尝试使用Spark 1.x编写的代码,并且不再支持Spark 2.0:

> in 1.x DataFrame.map是((Row)?T)(ClassTag [T])?RDD [T]
> in 2.x数据集[Row] .map是((Row)?T)(Encoder [T])?数据集[T]

说实话,在1.x也没有什么意义.独立于版本,您可以简单地使用DataFrame API:

import org.apache.spark.sql.functions.{when,lower}

val df = Seq(
  (2012,"Tesla","S"),(1997,"Ford","E350"),(2015,"Chevy","Volt")
).toDF("year","make","model")

df.withColumn("make",when(lower($"make") === "tesla","S").otherwise($"make"))

如果你真的想使用map,你应该使用静态类型的数据集:

import spark.implicits._

case class Record(year: Int,make: String,model: String)

df.as[Record].map {
  case tesla if tesla.make.toLowerCase == "tesla" => tesla.copy(make = "S")
  case rec => rec
}

或至少返回一个具有隐式编码器的对象:

df.map {
  case Row(year: Int,model: String) => 
    (year,if(make.toLowerCase == "tesla") "S" else make,model)
}

最后,如果一些完全疯狂的原因,你真的想映射Dataset [Row],你必须提供所需的编码器:

import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row

// Yup,it would be possible to reuse df.schema here
val schema = StructType(Seq(
  StructField("year",IntegerType),StructField("make",StringType),StructField("model",StringType)
))

val encoder = RowEncoder(schema)

df.map {
  case Row(year,model) if make.toLowerCase == "tesla" => 
    Row(year,"S",model)
  case row => row
} (encoder)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读