簡體   English   中英

根據關鍵列值 pandas 將一個數據幀中的行與另一個數據幀匹配

[英]Match rows in one data frame to another based on key column values pandas

我有兩個數據框(A 和 B),分別代表事務的兩側,分別有 m 行和 n 行。 有幾個關鍵列可以唯一標識這些事務。 我需要找到 row_in_A 和 row_in_B 以使這些鍵列對兩者相等,其余列無關緊要。 然后我需要從各自的 dfs 中刪除這些行。

前:

在一個:

Seller | Buyer | Side A
----------------------
  X    |   Y   | True
  C    |   D   | True

在 B 中:

Seller | Buyer | Side B
----------------------
  X    |   Y   | True

假設關鍵列只有賣方和買方,這些行應該匹配並隨后從 A 和 B 中刪除。這些列可以/將包含兩個 dfs 中的重復條目。

后:

Seller | Buyer | Side A
----------------------
  C    |   D   | True

我該怎么做呢?

SellerBuyer列創建一個MultiIndex ,然后使用MultiIndex.isin創建一個 boolean 掩碼,使用此掩碼過濾行:

i1 = pd.MultiIndex.from_arrays([df1['Seller'], df1['Buyer']])
i2 = pd.MultiIndex.from_arrays([df2['Seller'], df2['Buyer']])

df1, df2 = df1[~i1.isin(i2)], df2[~i2.isin(i1)]

使用DataFrame.set_index類似想法:

i1 = df1.set_index(['Seller', 'Buyer']).index
i2 = df2.set_index(['Seller', 'Buyer']).index

df1, df2 = df1[~i1.isin(i2)], df2[~i2.isin(i1)]

結果:

print(df1)
  Seller Buyer  Side A
1      C     D    True

暫無
暫無

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

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