spark - scala:不是org.apache.spark.sql.Row的成员

Eda*_*ame 7 scala apache-spark rdd apache-spark-sql spark-dataframe

我试图将数据帧转换为RDD,然后执行下面的一些操作以返回元组:

df.rdd.map { t=>
 (t._2 + "_" + t._3 , t)
}.take(5)
Run Code Online (Sandbox Code Playgroud)

然后我得到了下面的错误.有人有主意吗?谢谢!

<console>:37: error: value _2 is not a member of org.apache.spark.sql.Row
               (t._2 + "_" + t._3 , t)
                  ^
Run Code Online (Sandbox Code Playgroud)

Dan*_*ula 11

当您将DataFrame转换为RDD时,您会得到一个RDD[Row],所以当您使用时map,您的函数会收到一个Rowas参数.因此,您必须使用Row方法来访问其成员(请注意,索引从0开始):

df.rdd.map { 
  row: Row => (row.getString(1) + "_" + row.getString(2), row)
}.take(5)
Run Code Online (Sandbox Code Playgroud)

您可以查看更多示例并检查Spark scaladoc中可用于Row对象的所有方法.

编辑:我不知道您执行此操作的原因,但是为了连接DataFrame的String列,您可以考虑以下选项:

import org.apache.spark.sql.functions._
val newDF = df.withColumn("concat", concat(df("col2"), lit("_"), df("col3")))
Run Code Online (Sandbox Code Playgroud)


Alb*_*nto 7

您可以访问行的每个元素,如果它是List或者Array,它意味着使用(index),但您也可以使用该方法get.

例如:

df.rdd.map {t =>
  (t(2).toString + "_" + t(3).toString, t)
}.take(5)
Run Code Online (Sandbox Code Playgroud)