在 Spark scala 中将行转换为列表

Mr.*_*ysl 2 scala dataframe apache-spark

可以这样做吗?我的数据框中的所有数据(~1000 列)都是双精度数,我想知道是否可以将一行数据转换为双精度数列表?

Psi*_*dom 5

您可以在 Row 上使用toSeq方法,然后将类型从 转换Seq[Any]Seq[Double](如果您确定所有列的数据类型都是 Double):

val df = Seq((1.0,2.0),(2.1,2.2)).toDF("A", "B")
// df: org.apache.spark.sql.DataFrame = [A: double, B: double]

df.show
+---+---+
|  A|  B|
+---+---+
|1.0|2.0|
|2.1|2.2|
+---+---+

df.first.toSeq.asInstanceOf[Seq[Double]]
// res1: Seq[Double] = WrappedArray(1.0, 2.0)
Run Code Online (Sandbox Code Playgroud)

如果您有 String 类型列,请使用toSeq然后与模式匹配一​​起使用将Stringmap转换为Double

val df = Seq((1.0,"2.0"),(2.1,"2.2")).toDF("A", "B")
// df: org.apache.spark.sql.DataFrame = [A: double, B: string]

df.first.toSeq.map{ 
    case x: String => x.toDouble
    case x: Double => x 
}
// res3: Seq[Double] = ArrayBuffer(1.0, 2.0)
Run Code Online (Sandbox Code Playgroud)