如何将 Scala 数据框中的所有十进制列转换为双精度类型?

gsm*_*113 0 scala apache-spark apache-spark-sql

我有一个十进制和字符串类型的数据框。我想将所有十进制列转换为 double 而不命名它们。我试过这个没有成功。有点新的火花。

>df.printSchema

root

 |-- var1: decimal(38,10) (nullable = true)
 |-- var2: decimal(38,10) (nullable = true)
 |-- var3: decimal(38,10) (nullable = true)
…
150 more decimal and string columns
Run Code Online (Sandbox Code Playgroud)

我尝试:

import org.apache.spark.sql.types._

val cols = df.columns.map(x => {
    if (x.dataType == DecimalType(38,0)) col(x).cast(DoubleType) 
    else col(x)
})
Run Code Online (Sandbox Code Playgroud)

我得到

<console>:30: error: value dataType is not a member of String
           if (x.dataType == DecimalType(38,0)) col(x).cast(DoubleType)
Run Code Online (Sandbox Code Playgroud)

abi*_*sis 5

这里的问题是df.columns将返回一个包含列名的字符串列表。另一方面,dataType 是StructField类的成员。要获得 DataType,您必须df.schema.fields改用。这会将字段列表公开为Array[StructField]

import org.apache.spark.sql.types.{StructField, DecimalType, DoubleType}
import org.apache.spark.sql.functions.col

val df = Seq(
(130, Decimal(122.45), "t1"),
(536, Decimal(1.45), "t2"),
(518, Decimal(0.45), "t3"))
.toDF("ID","decimal","tmp")

df.printSchema
// root
//  |-- ID: integer (nullable = false)
//  |-- decimal: decimal(38,18) (nullable = true)
//  |-- tmp: string (nullable = true)

val decimalSchema = df.schema.fields.map{f =>
  f match{
    case StructField(name:String, _:DecimalType, _, _) => col(name).cast(DoubleType)
    case _ => col(f.name)
  }
}

df.select(decimalSchema:_*).printSchema
// root
//  |-- ID: integer (nullable = false)
//  |-- decimal: double (nullable = true)
//  |-- tmp: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

Map 将返回一个列列表,其中 DecimalType 替换为 DoubleType。