Nir*_*r R 2 scala apache-spark
我有两个具有不同类型列的数据框。我需要加入这两个不同的数据框。请参考下面的例子
val df1 has
Customer_name
Customer_phone
Customer_age
val df2 has
Order_name
Order_ID
Run Code Online (Sandbox Code Playgroud)
这两个数据框没有任何公共列。两个数据框中的行数和列数也不同。我试图插入一个新的虚拟列来增加 row_index 值,如下所示 val dfr=df1.withColumn("row_index",monotonically_increasing_id())。
但是当我使用 Spark 2 时,不支持 monotonically_increasing_id 方法。有什么方法可以连接两个数据框,以便我可以在一张 Excel 文件中创建两个数据框的值。
例如
val df1:
Customer_name Customer_phone Customer_age
karti 9685684551 24
raja 8595456552 22
val df2:
Order_name Order_ID
watch 1
cattoy 2
Run Code Online (Sandbox Code Playgroud)
我的最终 excel 表应该是这样的:
Customer_name Customer_phone Customer_age Order_name Order_ID
karti 9685684551 24 watch 1
raja 8595456552 22 cattoy 2
Run Code Online (Sandbox Code Playgroud)
monotonically_increasing_id()
是递增且唯一的,但不连续。
您可以zipWithIndex
通过转换为rdd
并重建具有相同架构的 Dataframe来使用dataframe
。
import spark.implicits._
val df1 = Seq(
("karti", "9685684551", 24),
("raja", "8595456552", 22)
).toDF("Customer_name", "Customer_phone", "Customer_age")
val df2 = Seq(
("watch", 1),
("cattoy", 2)
).toDF("Order_name", "Order_ID")
val df11 = spark.sqlContext.createDataFrame(
df1.rdd.zipWithIndex.map {
case (row, index) => Row.fromSeq(row.toSeq :+ index)
},
// Create schema for index column
StructType(df1.schema.fields :+ StructField("index", LongType, false))
)
val df22 = spark.sqlContext.createDataFrame(
df2.rdd.zipWithIndex.map {
case (row, index) => Row.fromSeq(row.toSeq :+ index)
},
// Create schema for index column
StructType(df2.schema.fields :+ StructField("index", LongType, false))
)
Run Code Online (Sandbox Code Playgroud)
现在加入最终的数据框
df11.join(df22, Seq("index")).drop("index")
Run Code Online (Sandbox Code Playgroud)
输出:
+-------------+--------------+------------+----------+--------+
|Customer_name|Customer_phone|Customer_age|Order_name|Order_ID|
+-------------+--------------+------------+----------+--------+
|karti |9685684551 |24 |watch |1 |
|raja |8595456552 |22 |cattoy |2 |
+-------------+--------------+------------+----------+--------+
Run Code Online (Sandbox Code Playgroud)
使用以下代码向两个数据框添加索引列
df1.withColumn("id1",monotonicallyIncreasingId)
df2.withColumn("id2",monotonicallyIncreasingId)
Run Code Online (Sandbox Code Playgroud)
然后使用以下代码连接两个数据帧并删除索引列
df1.join(df2,col("id1")===col("id2"),"inner")
.drop("id1","id2")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8099 次 |
最近记录: |