我有一个数据帧(dataDF(,其中包含以下数据:
firstColumn;secondColumn;thirdColumn
myText;123;2010-08-12 00:00:00
在我的例子中,所有这些列都是StringType。
另一方面,我有另一个DataFrame(customTypeDF(,它可以修改,并为一些列包含自定义类型,如:
columnName;customType
secondColumn;IntegerType
thirdColumn; TimestampType
如何在dataDF数据帧上动态应用新类型?
您可以使用作为Seq:收集的customTypeDF映射列名
val colTypes = customTypeDF.rdd.map(x => x.toSeq.asInstanceOf[Seq[String]]).collect
val result = dataDF.select(
dataDF.columns.map(c =>
if (colTypes.map(_(0)).contains(c))
col(c).cast(colTypes.filter(_(0) == c)(0)(1).toLowerCase.replace("type","")).as(c)
else col(c)
):_*
)
result.show
+-----------+------------+-------------------+
|firstColumn|secondColumn| thirdColumn|
+-----------+------------+-------------------+
| myText| 123|2010-08-12 00:00:00|
+-----------+------------+-------------------+
result.printSchema
root
|-- firstColumn: string (nullable = true)
|-- secondColumn: integer (nullable = true)
|-- thirdColumn: timestamp (nullable = true)