簡體   English   中英

在 Spark 中加入具有不同記錄和大小的兩個數據幀

[英]Join two dataframes with different records and size in Spark

似乎這個問題被問了幾次,但在以前的問題中提出的解決方案對我不起作用。

我有兩個不同尺寸的數據框,如下圖所示。 secondfirst是表一的一部分,但經過一些處理后,我又添加了一列column4 現在,我想加入這兩個表,這樣我有三個表Required加盟后。

嘗試過的東西。

所以我做了幾個不同的解決方案,但沒有一個適合我。

我試過

val required =first.join(second, first("PDE_HDR_CMS_RCD_NUM") === second("PDE_HDR_CMS_RCD_NUM") , "left_outer")

我也試過

val required = first.withColumn("SEQ", when(second.col("PDE_HDR_FILE_ID") === (first.col("PDE_HDR_FILE_ID").alias("PDE_HDR_FILE_ID1")), second.col("uniqueID")).otherwise(lit(0)))

在第二次嘗試中,我在收到錯誤.alias后使用了.alias

提取過程中發生錯誤。 錯誤:org.apache.spark.sql.AnalysisException:已解析的屬性(s)uniqueID#775L 缺失。

感謝您花時間閱讀我的問題

在此處輸入圖片說明

要生成所需的結果,您應該在第一個表中的行標識列上連接兩個表。 假設c1 + c2 + c3唯一標識第一個表中的每一行,以下是使用部分樣本數據集的示例:

import org.apache.spark.sql.functions._
import spark.implicits._

val df1 = Seq(
  (1, "e", "o"),
  (4, "d", "t"),
  (3, "f", "e"),
  (2, "r", "r"),
  (6, "y", "f"),
  (5, "t", "g"),
  (1, "g", "h"),
  (4, "f", "j"),
  (6, "d", "k"),
  (7, "s", "o")
).toDF("c1", "c2", "c3")

val df2 = Seq(
  (3, "f", "e", 444),
  (5, "t", "g", 555),
  (7, "s", "o", 666)
).toDF("c1", "c2", "c3", "c4")

df1.join(df2, Seq("c1", "c2", "c3"), "left_outer").show
// +---+---+---+----+
// | c1| c2| c3|  c4|
// +---+---+---+----+
// |  1|  e|  o|null|
// |  4|  d|  t|null|
// |  3|  f|  e| 444|
// |  2|  r|  r|null|
// |  6|  y|  f|null|
// |  5|  t|  g| 555|
// |  1|  g|  h|null|
// |  4|  f|  j|null|
// |  6|  d|  k|null|
// |  7|  s|  o| 666|
// +---+---+---+----+

暫無
暫無

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

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