scala - 根据另一个数据框的行值在数据框中添加新列
问题描述
我需要向数据框中添加一个新列,DF1
但新列的值应使用该DF
. 要使用的其他哪些列将在另一个数据框中给出DF2
。
例如。DF1
|protocolNo|serialNum|testMethod |testProperty|
+----------+---------+------------+------------+
|Product1 | AB |testMethod1 | TP1 |
|Product2 | CD |testMethod2 | TP2 |
DF2-
|action| type| value | exploded |
+------------+---------------------------+-----------------+
|append|hash | [protocolNo] | protocolNo |
|append|text | _ | _ |
|append|hash | [serialNum,testProperty] | serialNum |
|append|hash | [serialNum,testProperty] | testProperty |
现在,如果列类型的值为hash ,则展开列的值DF2
将是列名。DF1
Required
- 应在 DF1 中创建新列。该值应计算如下 -
hash[protocolNo]_hash[serialNumTestProperty]
~~~这里就列的地方他们对应的行值应该来了。
例如。对于 DF1 的第 1 行,列值应为
hash[Product1]_hash[ABTP1]
这将abc-df_egh-45e
在散列后产生类似的结果。
DF1 的每一行都应遵循上述程序。
我尝试在 DF1 上使用 UDF 使用 map 和 withColumn 函数。但是在 UDF 中,外部数据帧值不可访问(给出空指针异常],我也无法将 DataFrame 作为 UDF 的输入。
如上所述,输入 DF 将是 DF1 和 DF2。
所需输出 DF-
|protocolNo|serialNum|testMethod |testProperty| newColumn |
+----------+---------+------------+------------+----------------+
|Product1 | AB |testMethod1 | TP1 | abc-df_egh-4je |
|Product2 | CD |testMethod2 | TP2 | dfg-df_ijk-r56 |
newColumn值在散列之后
解决方案
代替 DF2,您可以将 DF2 转换为像 Specifications 这样的案例类,例如
case class Spec(columnName:String,inputColumns:Seq[String],action:String,action:String,type:String*){}
创建上述类的实例
val specifications = Seq(
Spec("new_col_name",Seq("serialNum","testProperty"),"hash","append")
)
然后你可以处理下面的列
val transformed = specifications
.foldLeft(dtFrm)((df: DataFrame, spec: Specification) => df.transform(transformColumn(columnSpec)))
def transformColumn(spec: Spec)(df: DataFrame): DataFrame = {
spec.type.foldLeft(df)((df: DataFrame, type : String) => {
type match {
case "append" => {have a case match of the action and do that , then append with df.withColumn}
}
}
语法可能不正确
推荐阅读
- python - 删除变量(指针)值不会删除它指向的值
- c - 使用 Clickone 发布后无法运行应用程序
- rest - 如何在我的流星应用程序的两个不同包中拥有具有相同 URL 的两条不同路由?
- ios - DispatchQueue.global(qos: .default) 在应用程序后台或屏幕锁定时继续,如何暂停?
- ios - 如何使用swift在折线图中显示json数据
- javascript - 如何限制在使用 ngx-datatable 创建的表中不重新排序列但所有剩余列必须是可重新排序的
- asp.net-core - .net core 3.0 中 BackgroundService 的通用工作者
- apache-kafka - 由于 FileSystemException,Kafka JUnit 测试失败
- angular - 如何在 WebMethodAdaptor 或 Http 帖子中添加值作为附加参数?
- android - 当我点击验证链接时打开应用程序