首页 > 解决方案 > 将两个 DataFrame 映射到一个新的 Schema'd Dataframe

问题描述

我正在尝试找到一种有效且干净的方法来在其他两个 DataFrame 中创建模式化的 DataFrame。

数据帧一(fNameDF):

+---------+
| fName   |
+---------+
| Paul    |
| Bob     |
| George  |
+---------+

数据帧二(lNameDF):

+---------+
| lName   |
+---------+
| Rimerman|
| King    |
| Reed    |
+---------+

结果:DataFrame 3(combinedDF):

val combinedSchema: StructType = new StructType()
.add(StructField("fullName", StringType, nullable = true))
.add(StructField("phoneNumber", StringType, nullable = true))

+-----------------+--------------+
|     fullName    | phoneNumber  |
+-----------------+--------------+
| Paul Rimerman   |     null     |
| Paul King       |     null     |
| Paul Reed       |     null     |
| Bob Rimerman    |     null     |
| Bob King        |     null     |
| Bob Reed        |     null     |
| George Rimerman |     null     |
| George King     |     null     |
| George Reed     |     null     |
+-----------------+--------------+

我尝试过 - 没有运气 - 使用嵌套映射操作完成上述操作,但感觉好像有更简单的方法可以做到这一点?

val combinedDF = fNameDF.map(fNameRow => { lNameDF.map(lNameRow => 
{ val fullName = concat(fNameDF.getString(0),lit(" "), lNameDF.getString(0))})}).schema(combinedSchema)

标签: scalaapache-sparkapache-spark-sql

解决方案


你可以使用这个full join

scala> var df = Seq(("Rimerman"),("King"),("ReedReed"),("Mahesh")).toDF("lname").withColumn("id",lit(1))

scala> df.show()
+--------+---+
|   lname| id|
+--------+---+
|Rimerman|  1|
|    King|  1|
|ReedReed|  1|
|  Mahesh|  1|
+--------+---+

为了更好地理解,您可以从语句中删除drop子句join

scala> var df2 = Seq(("George"),("Bob"),("Paul")).toDF("fname").withColumn("id",lit(1))

scala> df2.show
+------+---+
| fname| id|
+------+---+
|George|  1|
|   Bob|  1|
|  Paul|  1|
+------+---+

scala> df.join(df2,Seq("id"),"full").drop("id").withColumn("full_name",concat(col("fname"),lit(" "),col("lname"))).withColumn("phone_number",lit("Null")).drop("lname","fname").orderBy(col("full_name")).show

+---------------+------------+
|      full_name|phone_number|
+---------------+------------+
|       Bob King|        Null|
|     Bob Mahesh|        Null|
|   Bob ReedReed|        Null|
|   Bob Rimerman|        Null|
|    George King|        Null|
|  George Mahesh|        Null|
|George ReedReed|        Null|
|George Rimerman|        Null|
|      Paul King|        Null|
|    Paul Mahesh|        Null|
|  Paul ReedReed|        Null|
|  Paul Rimerman|        Null|
+---------------+------------+

希望它可以帮助你。


推荐阅读