Spark DataFrame根据列条件更改数据类型

Ume*_*cha 2 scala apache-spark apache-spark-sql

我有一个大约1000列的Spark DataFrame df1,所有String类型列.现在我想根据列名的条件将df1的列类型从字符串转换为其他类型,如double,int等.例如,假设df1只有三列字符串类型

df1.printSchema

col1_term1: String
col2_term2: String 
col3_term3: String
Run Code Online (Sandbox Code Playgroud)

更改列类型的条件是,如果col name包含term1,则将其更改为int,如果col name包含term2,则将其更改为double,依此类推.我是Spark的新手.

Psi*_*dom 7

您可以简单地映射列,并根据列名将列转换为正确的数据类型:

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

val df = Seq(("1", "2", "3"), ("2", "3", "4")).toDF("col1_term1", "col2_term2", "col3_term3")

val cols = df.columns.map(x => {
    if (x.contains("term1")) col(x).cast(IntegerType) 
    else if (x.contains("term2")) col(x).cast(DoubleType) 
    else col(x)
})

df.select(cols: _*).printSchema
root
 |-- col1_term1: integer (nullable = true)
 |-- col2_term2: double (nullable = true)
 |-- col3_term3: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)