scala - 将两个 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)
解决方案
你可以使用这个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|
+---------------+------------+
希望它可以帮助你。
推荐阅读
- javascript - 实现@keyframes CSS 动画的问题
- python - 在多列中按类别计算数据帧值
- r - Tidyverse 没有安装
- python-2.7 - 如何提示用户输入并只允许数字响应(在 Python 2.7 中)
- python - 嗨,我正在编写一个机器人来填写 HTML 表单。对值和有效负载有一些疑问
- go - 使用 Go 后端的 net::ERR_CERT_INVALID
- android - 在 kotlin 中向表格布局添加行
- python - JointDistributionSequential 样本的对数概率上的 Tensorflow 概率不兼容形状错误
- python - 如何将 for 循环中的值添加到数据框列中?
- javascript - 使用值对按对象数组过滤