[英]Spark / Scala - Compare Two Columns In a Dataframe when one is NULL
[英]Compare the values in multiple columns in one Dataframe with multiple rows in one single column for target dataframe for the same record in Scala?
我的源和目标是这样的
来源 DataFrame
key col1 col2 col3 col4 col5 col6
1 AA BB CC null null null
2 SS null null null null null
3 AA CC RR SS DD null
目标 DataFrame
Key Column
1 AA
1 BB
1 CC
2 SS
3 AA
....
我想比较这两个值以检查它们是否正确填充并且没有重复。 我尝试了几种方法,但都很慢,
我尝试的一种方法是:
sourceArray.sameElements(targetArray)
有没有简单的解决方案。 我想我把这个简单的问题复杂化了。
您可以从除key
之外的所有列创建数组,过滤数组中的 null 值,然后将其分解:
val df1 = df.withColumn(
"Column",
array(df.columns.filter(_!="key").map(col(_)):_*)
).select(
col("key"),
explode(expr("filter(Column, x -> x is not null)")).as("Column")
)
df1.show
//+---+------+
//|key|Column|
//+---+------+
//| 1| AA|
//| 1| BB|
//| 1| CC|
//| 2| SS|
//| 3| AA|
//| 3| CC|
//| 3| RR|
//| 3| SS|
//| 3| DD|
//+---+------+
或者简单地使用stack
表达式取消透视列然后过滤掉空值:
val df1 = df.selectExpr(
"key",
"stack(6, col1, col2, col3, col4, col5, col6) as Column"
).filter("Column is not null")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.