簡體   English   中英

按多列比較熊貓數據框

[英]Compare pandas dataframes by multiple columns

找出兩個數據框基於多列組合的不同之處的最佳方法是什么。 所以,如果我有以下內容:

DF1:

  A B C
0 1 2 3
1 3 4 2

DF2:

  A B C
0 1 2 3
1 3 5 2

想要顯示上面示例中存在(3,4,2)與(3,5,2)之類的差異的所有行。 我嘗試使用pd.merge()來思考,如果我將所有列都用作使用外部聯接進行聯接的鍵,則最終會得到可以幫助我獲得所需內容的數據框,但事實並非如此。

多虧了EdChum,我可以使用如下所示的布爾差異掩碼,但首先必須確保索引具有可比性。

df1 = df1.set_index('A')
df2 = df2.set_index('A') #this gave me a nice index using one of the keys.
                  #if there are different rows than I would get nulls. 
df1 = df1.reindex_like(df2)
df1[~(df1==df2).all(axis=1)] #this gave me all rows that differed. 

我們可以使用.all並傳遞axis=1來執行行比較,然后可以使用此布爾索引通過取反~布爾索引來顯示不同的行:

In [43]:

df[~(df==df1).all(axis=1)]
Out[43]:
   A  B  C
1  3  4  2

分解:

In [44]:

df==df1
Out[44]:
      A      B     C
0  True   True  True
1  True  False  True
In [45]:

(df==df1).all(axis=1)
Out[45]:
0     True
1    False
dtype: bool

然后,我們可以將上述內容作為布爾索引傳遞給df ,並使用~對其進行反轉

暫無
暫無

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

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