繁体   English   中英

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

[英]Spark DataFrame change datatype based on column condition

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

df1.printSchema

col1_term1: String
col2_term2: String 
col3_term3: String

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

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

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)

虽然它不会产生任何不同于@Psidom提出的解决方案的结果 ,你也可以使用一些Scala语法 -像这样的糖

val modifiedDf: DataFrame = originalDf.columns.foldLeft[DataFrame](originalDf) { (tmpDf: DataFrame, colName: String) =>
  if (colName.contains("term1")) tmpDf.withColumn(colName, tmpDf(colName).cast(IntegerType))
  else if (colName.contains("term2")) tmpDf.withColumn(colName, tmpDf(colName).cast(DoubleType))
  else tmpDf
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM