簡體   English   中英

PySpark:如果在第二個 dataframe 中找不到列值,則將行從一個 dataframe 移到另一個

[英]PySpark: Moving rows from one dataframe into another if column values are not found in second dataframe

我有兩個具有相似模式的 spark 數據幀:DF1:

id       category  flag
123abc   type 1     1 
456def   type 1     1
789ghi   type 2     0
101jkl   type 3     0

DF2:

id       category  flag
123abc   type 1     1 
456def   type 1     1
789ghi   type 2     1
101xyz   type 3     0

DF1 的數據比 DF2 多,所以我無法替換它。 但是,DF2 會有 DF1 沒有的 id,還有幾個 flag 數據更准確的 id。 這意味着我需要解決兩種情況:

  1. 789ghi有不同的標志,需要覆蓋 DF1 中的 789ghi。
  2. 101xyz在DF1中找不到,需要移過來

每個 dataframe 都是數百萬行,所以我正在尋找一種有效的方法來執行此操作。 我不確定這是需要外部連接還是反連接的情況。

您可以合並兩個數據框並為每個 id 保留第一條記錄。

from functools import reduce
from pyspark.sql import DataFrame, Window
from pyspark.sql.functions import monotonically_increasing_id, col

df = reduce(DataFrame.unionByName,[df2,df1])

df = df.withColumn('row_num',monotonically_increasing_id())

window = Window.partitionBy("id").orderBy('row_num')

df = (df.withColumn('rank', rank().over(window))
        .filter(col('rank') == 1)).drop('rank','row_num')

Output

+------+--------+----+
|    id|category|flag|
+------+--------+----+
|101jkl|  type 3|   0|
|101xyz|  type 3|   0|
|123abc|  type 1|   1|
|456def|  type 1|   1|
|789ghi|  type 2|   1|
+------+--------+----+

選項 1:我會在 df1 而不是 df2 中找到 id,然后將它們放入子集 df 中,然后將子集與 df2 合並。

或者

選項 2:在 df1 中查找 df2 中的元素並刪除這些行,然后合並 df2。 我采用的方法顯然是基於計算成本較低的方法。

選項 1 代碼

s=df1.select('id').subtract(df2.select('id')).collect()[0][0]

df2.union(df1.filter(col('id')==s)).show()

結果

+------+--------+----+
|    id|category|flag|
+------+--------+----+
|123abc|  type 1|   1|
|456def|  type 1|   1|
|789ghi|  type 2|   1|
|101xyz|  type 3|   0|
|101jkl|  type 3|   0|
+------+--------+----+

暫無
暫無

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

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