scala - 如何使用 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
任何帮助将不胜感激。谢谢!
解决方案
尝试这个 -
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)))
}
推荐阅读
- android - Android 库 (jar/aar) 可以用于 Xamarin 中的 iOS
- javascript - 如何设置对象(object)的默认属性?
- typescript - 在保留参数的同时更改函数返回类型
- amazon-web-services - 在适用于 C++ 的 AWS s3 开发工具包中执行 PutObjectCallableRequest
- python - pandas multiindex的条形图:栈第一级
- angular - 错误:未定义导出 - Nativescript
- java - 尝试从 Ignite 缓存中获取值时出现“org.apache.ignite.cache.CacheServerNotFoundException 错误”
- intellij-idea - IntelliJ 不识别“让”
- android - Dagger2 对 applicationComponent 的依赖引用未提供要注入的对象
- java - 为什么非阻塞并发优于阻塞并发