问题描述
有两个表;一个是ID表1,另一个是属性表2.
There are two tables; one is ID Table 1 and the other is Attribute Table 2.
表1
表2
如果表1中同一行的ID具有相同的属性,则得到数字1,否则得到0.最后,得到结果表3.
If the IDs the same row in Table 1 has same attribrte, then we get number 1, else we get 0. Finally, we get the result Table 3.
表3
例如,id1和id2具有不同的颜色和大小,因此id1和id2行(表3中的第二行)具有"id1 id2 0 0";
For example, id1 and id2 have different color and size, so the id1 and id2 row(2nd row in Table 3) has "id1 id2 0 0";
id1和id3具有相同的颜色和不同的大小,因此id1和id3行(表3中的第3行)具有"id1 id3 1 0";
id1 and id3 have same color and different size, so the id1 and id3 row(3nd row in Table 3) has "id1 id3 1 0";
相同属性--- 1不同的属性--0
Same attribute---1Different attribute---0
如何使用Scala数据框获得结果表3?
How can I get the result Table 3 using Scala dataframe?
推荐答案
这应该可以解决问题
import spark.implicits._
val t1 = List(
("id1","id2"),
("id1","id3"),
("id2","id3")
).toDF("id_x", "id_y")
val t2 = List(
("id1","blue","m"),
("id2","red","s"),
("id3","blue","s")
).toDF("id", "color", "size")
t1
.join(t2.as("x"), $"id_x" === $"x.id", "inner")
.join(t2.as("y"), $"id_y" === $"y.id", "inner")
.select(
'id_x,
'id_y,
when($"x.color" === $"y.color",1).otherwise(0).alias("color").cast(IntegerType),
when($"x.size" === $"y.size",1).otherwise(0).alias("size").cast(IntegerType)
)
.show()
结果:
+----+----+-----+----+
|id_x|id_y|color|size|
+----+----+-----+----+
| id1| id2| 0| 0|
| id1| id3| 1| 0|
| id2| id3| 0| 1|
+----+----+-----+----+
这篇关于如何使用Scala的DataFrame比较表中的每一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!