Scala 在没有公共列的情况下连接两个数据帧
我有两个数据帧,它们有不同类型的列。我需要连接这两个不同的数据帧。请参考下面的例子Scala 在没有公共列的情况下连接两个数据帧,scala,apache-spark,Scala,Apache Spark,我有两个数据帧,它们有不同类型的列。我需要连接这两个不同的数据帧。请参考下面的例子 val df1 has Customer_name Customer_phone Customer_age val df2 has Order_name Order_ID 这两个数据帧没有任何公共列。两个数据帧中的行数和列数也不同。我尝试插入一个新的伪列以增加行索引值,如下所示 val dfr=df1.withColumn(“行索引”,单调递增的id()) 但由于我使用的是Spark 2,所以不支持单调递增
val df1 has
Customer_name
Customer_phone
Customer_age
val df2 has
Order_name
Order_ID
这两个数据帧没有任何公共列。两个数据帧中的行数和列数也不同。我尝试插入一个新的伪列以增加行索引值,如下所示
val dfr=df1.withColumn(“行索引”,单调递增的id())
但由于我使用的是Spark 2,所以不支持单调递增的id方法。有没有办法连接两个dataframe,这样我就可以在一张excel文件中创建两个dataframe的值
比如说
val df1:
Customer_name Customer_phone Customer_age
karti 9685684551 24
raja 8595456552 22
val df2:
Order_name Order_ID
watch 1
cattoy 2
我的最终excel表应如下所示:
Customer_name Customer_phone Customer_age Order_name Order_ID
karti 9685684551 24 watch 1
raja 8595456552 22 cattoy 2
单调递增的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))
)
现在加入最后的数据帧
df11.join(df22, Seq("index")).drop("index")
输出:
+-------------+--------------+------------+----------+--------+
|Customer_name|Customer_phone|Customer_age|Order_name|Order_ID|
+-------------+--------------+------------+----------+--------+
|karti |9685684551 |24 |watch |1 |
|raja |8595456552 |22 |cattoy |2 |
+-------------+--------------+------------+----------+--------+
使用以下代码向两个数据帧添加索引列
df1.withColumn("id1",monotonicallyIncreasingId)
df2.withColumn("id2",monotonicallyIncreasingId)
然后使用下面的代码连接两个数据帧并删除索引列
df1.join(df2,col("id1")===col("id2"),"inner")
.drop("id1","id2")
这有点复杂和冗长@ss301的答案更简单。我建议使用单调递增id,因为单调递增id不受欢迎