给定两个数据帧,这两个数据帧可能具有完全不同的模式,除了索引列(本例中为timestamp
),例如下面的df1和df2:
df1:
timestamp | length | width
1 | 10 | 20
3 | 5 | 3
df2:
timestamp | name | length
0 | "sample" | 3
2 | "test" | 6
我如何将这两个数据帧组合成一个如下所示的数据帧:
df3:
timestamp | df1 | df2
| length | width | name | length
0 | null | null | "sample" | 3
1 | 10 | 20 | null | null
2 | null | null | "test" | 6
3 | 5 | 3 | null | null
我对spark非常陌生,所以这可能不是很有意义。但我试图解决的问题是:我需要组合这些数据帧,以便稍后可以将每一行转换为给定的对象。但是,它们必须按时间戳排序,所以当我写出这些对象时,它们的顺序是正确的。
因此,例如,给定上面的df3
,我将能够生成以下对象列表:
objs = [
ObjectType1(timestamp=0, name="sample", length=3),
ObjectType2(timestamp=1, length=10, width=20),
ObjectType1(timestamp=2, name="test", length=6),
ObjectType2(timestamp=3, length=5, width=3)
]
也许组合数据帧没有意义,但我如何对数据帧进行单独排序,并以某种方式从按timestamp
全局排序的每个数据帧中获取Row
?
附注:请注意,我在两个数据帧中都重复了length
。这样做是为了说明它们可能具有相同名称和类型的列,但表示完全不同的数据,因此合并模式是不可能的。
发布于 2019-03-27 07:55:28
您需要的是一个完整的外连接,可能会重命名其中一列,如df1.join(df2.withColumnRenamed("length","length2"), Seq("timestamp"),"full_outer")
请看这个例子,它是由你自己构建的(只需要更少的输入)
// data shaped as your example
case class t1(ts:Int, width:Int,l:Int)
case class t2(ts:Int, width:Int,l:Int)
// create data frames
val df1 = Seq(t1(1,10,20),t1(3,5,3)).toDF
val df2 = Seq(t2(0,"sample",3),t2(2,"test",6)).toDF
df1.join(df2.withColumnRenamed("l","l2"),Seq("ts"),"full_outer").sort("ts").show
+---+-----+----+------+----+
| ts|width| l| name| l2|
+---+-----+----+------+----+
| 0| null|null|sample| 3|
| 1| 10| 20| null|null|
| 2| null|null| test| 6|
| 3| 5| 3| null|null|
+---+-----+----+------+----+
https://stackoverflow.com/questions/55367446
复制相似问题