如何使用 Scala 的 DataFrame 比较表中的每一列 [英] How do I compare each column in a table using DataFrame by Scala

查看:36
本文介绍了如何使用 Scala 的 DataFrame 比较表中的每一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两张桌子;一个是ID表1,另一个是属性表2.

There are two tables; one is ID Table 1 and the other is Attribute Table 2.

表一

表 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中的第2行)有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---1 Different 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 比较表中的每一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆