我之前提出的问题如下。 Last question
表1 - ID对表
表2 - 属性表
表3
例如,id1和id2具有不同的颜色和大小,因此id1和id2行(表3中的第2行)具有" id1 id2 0 0&#34 ;;
id1和id3具有相同的颜色和不同的大小,因此id1和id3行(表3中的第3行)具有" id1 id3 1 0&#34 ;;
相同的属性--- 1个不同的属性--- 0
但是,如果我不知道Table2中有多少个属性列怎么办?我该怎么做?比如我不知道列名的颜色或大小。也许还有另一个名为品牌的专栏。那么我怎样才能获得Table3?
答案 0 :(得分:1)
以下解决方案适用于Table2
中任何未知数量的属性。我已根据您的Last Question
val t1 = List(
("id1","id2"),
("id1","id3"),
("id2","id3")
).toDF("id_x", "id_y")
val t2 = List(
("id1","blue","m","brand1"),
("id2","red","s","brand1"),
("id3","blue","s","brand2")
).toDF("id", "color", "size", "brand")
val outSchema = t2.columns.tail
var t3 = t1
.join(t2.as("x"), $"id_x" === $"x.id", "inner")
.join(t2.as("y"), $"id_y" === $"y.id", "inner")
for(columnName <- outSchema){
t3 = t3.withColumn(columnName+"s", when(col(s"x.$columnName") === col(s"y.$columnName"),1).otherwise(0))
.drop(columnName)
.drop("id")
.withColumnRenamed(columnName+"s", columnName)
}
t3.show(false)
最终输出是
+----+----+-----+----+-----+
|id_x|id_y|color|size|brand|
+----+----+-----+----+-----+
|id1 |id2 |0 |0 |1 |
|id1 |id3 |1 |0 |0 |
|id2 |id3 |0 |1 |0 |
+----+----+-----+----+-----+
该解决方案适用于任何未知数量的属性。