首页 > 解决方案 > 如何使用 Azure Databricks 上的 scala 在循环中将新列添加到数据框

问题描述

我已使用 scala 将 csv 文件导入 Azure Databricks 中的数据框。

--------------
A  B  C  D  E
--------------
a1 b1 c1 d1 e1
a2 b2 c2 d2 e2
--------------

现在我想对一些选择性列执行散列并将结果作为新列添加到该数据帧。

--------------------------------
A  B  B2       C  D  D2       E
--------------------------------
a1 b1 hash(b1) c1 d1 hash(d1) e1
a2 b2 hash(b2) c2 d2 hash(d2) e2
--------------------------------

这是我的代码:

val data_df = spark.read.format("csv").option("header", "true").option("sep", ",").load(input_file)
...
...
for (col <- columns) {
    if (columnMapping.keys.contains((col))){
        val newColName = col + "_token"
        // Now here I want to add a new column to data_df and the content would be hash of the current value
    }
}
// And here I would like to upload selective columns (B, B2, D, D2) to a SQL database

任何帮助将不胜感激。谢谢!

标签: scalaapache-sparkapache-spark-sqldatabricksazure-databricks

解决方案


尝试这个 -

val colsToApplyHash = Array("B","D")

val hashFunction:String => String = <ACTUAL HASH LOGIC>
val hash = udf(hashFunction)

val finalDf = colsToApplyHash.foldLeft(data_df){
  case(acc,colName) => acc.withColumn(colName+"2",hash(col(colName)))
}

推荐阅读