如何在scala spark dataFrame中将模式的数据类型转换为另一个模式



我有一个数据帧,其中不是IntegerType,而是在架构中有LongType,DataFrame以json格式存储。我应该如何将带有长型的所有列转换为整数型。

试试这个 -

df.select(df.schema.map(s => if (s.dataType == LongType) col(s.name).cast(IntegerType) else col(s.name)): _*)

如果它是一个小数据帧,您可以简单地强制转换所有列: (对于大型数据集,不建议这样做,因为这使用可变数据帧(

import org.apache.spark.sql.types.{IntegerType, LongType}
val cols = dataFrame.columns()
// mutable dataframe
var tmpDf = dataFrame
for(col <- cols){
if(dataFrame.schema(col).dataType == LongType){
tmpDf.withColumn(s"${col}_int", dataFrame[col].cast(IntegerType))
}
}
// convert back to immutable
val dataFrame_2 = tmpDf

最新更新