簡體   English   中英

從 scala 中其他 2 個數據集的特定列創建新數據集

[英]Create new dataset from specific columns from 2 other datasets in scala

我有以下 2 個不同模式的數據集。

case class schema1(a: Double, b: Double) -> dataset1
case class schema2(c: Double, d: Double, e: Double, f: Double) -> dataset2

我想創建另一個具有以下模式的數據集:

case class schema3(c: Double,  b: Double) -> dataset3

即 schema3 數據集包含來自模式 2 數據集的第一列 c 和來自模式 1 數據集的第二列 b。

如何利用來自數據集 2 和 1 的列 c 和 b 的數據創建基於 schema3 的第三個數據集。

或者更簡單地說,我必須通過從第一個數據集中獲取一列和從第二個數據集獲取另一列並將其映射到上面定義的第三個模式來創建第三個數據集。

請幫忙。

使用monotonically_increasing_idrow_numer在兩個數據集中添加唯一的 id 值並使用id列連接兩個數據集以及來自兩個數據集的所需列,最后從結果數據集中刪除 id。

請檢查以下代碼。

scala> case class schema1(a: Double, b: Double)
defined class schema1

scala> case class schema2(c: Double, d: Double, e: Double, f: Double)
defined class schema2

scala> import org.apache.spark.sql.expressions._
import org.apache.spark.sql.expressions._

scala> val sa = Seq(schema1(11,12),schema1(22,23)).toDF.withColumn("id",monotonically_increasing_id).withColumn("id",row_number().over(Window.orderBy("id")))
sa: org.apache.spark.sql.DataFrame = [a: double, b: double ... 1 more field]

scala> val sb = Seq(schema2(22,23,24,25),schema2(32,33,34,35),schema2(132,133,134,135)).toDF.withColumn("id",monotonically_increasing_id).withColumn("id",row_number().over(Window.orderBy("id")))
sb: org.apache.spark.sql.DataFrame = [c: double, d: double ... 3 more fields]

scala> sa.show(false)
+----+----+---+
|a   |b   |id |
+----+----+---+
|11.0|12.0|0  |
|22.0|23.0|1  |
+----+----+---+


scala> sb.show(false)
+-----+-----+-----+-----+---+
|c    |d    |e    |f    |id |
+-----+-----+-----+-----+---+
|22.0 |23.0 |24.0 |25.0 |0  |
|32.0 |33.0 |34.0 |35.0 |1  |
|132.0|133.0|134.0|135.0|2  |
+-----+-----+-----+-----+---+

scala> sb.select("c","id").join(sa.select("b","id"),Seq("id"),"full").drop("id").show(false)
+-----+----+
|c    |b   |
+-----+----+
|22.0 |12.0|
|32.0 |23.0|
|132.0|null|
+-----+----+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM