我有一个大约1000列的所有String类型列的Spark DataFrame df1。现在我想根据列名的条件将df1的column'类型从字符串转换为其他类型,例如double,int等。例如,假设df1只有三列字符串类型
df1.printSchema
col1_term1: String
col2_term2: String
col3_term3: String
更改列类型的条件是,如果col名称包含term1,则将其更改为int;如果col名称包含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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句