2016-04-27 35 views
20

Ho bisogno di confrontare due dataframe di diverse dimensioni in termini di righe e stampare righe non corrispondenti. Consente di prendere i due seguenti:Panda: Diff di due Dataframes

df1 = DataFrame({ 
'Buyer': ['Carl', 'Carl', 'Carl'], 
'Quantity': [18, 3, 5, ]}) 

df2 = DataFrame({ 
'Buyer': ['Carl', 'Mark', 'Carl', 'Carl'], 
'Quantity': [2, 1, 18, 5]}) 

Qual è il modo più efficiente per riga-saggio su DF2 e stampare file non in df1 esempio:

Buyer  Quantity 
Carl   2 
Mark   1 

Importante: Non voglio avere fila :

Buyer  Quantity 
Carl   3 

incluso nel diff:

ho già provato: 012. e Outputting difference in two Pandas dataframes side by side - highlighting the difference

Ma questi non corrispondono al mio problema.

Grazie

Andy

+0

Perché non esiste una risposta accettata? Anche lo script – famargar

risposta

43

merge i 2 DFS con il metodo 'esterna' e passare param indicator=True questo vi dirà se le righe sono presenti in entrambi/sinistra solo/solo a destra, è possibile filtrare DF fusa dopo:

In [22]: 
merged = df1.merge(df2, indicator=True, how='outer') 
merged[merged['_merge'] == 'right_only'] 

Out[22]: 
    Buyer Quantity  _merge 
3 Carl   2 right_only 
4 Mark   1 right_only 
+1

sopra mi ha aiutato, grazie – Plinus

+0

df3 = merged.loc [unito ['_ unione'] == 'left_only'] df3 .drop (['_ merge'], axis = 1, inplace = True) dando Warning (da avvertimenti modulo): file "D: /Work/psnl/python/pyCharm/compare2RSfile.py", linea 1 import os, sys, ntpath, stringa, datetime, winsound, tempo SettingWithCopyWarning: Un valore sta cercando di essere impostato su una copia di una sezione da un DataFrame, come superare questo avviso – Plinus

+0

anche se dà lo stesso avviso se aggiungi un nuovo campo, df3 ['Valore'] = '' – Plinus

1
diff = set(zip(df2.Buyer, df2.Quantity)) - set(zip(df1.Buyer, df1.Quantity)) 

Questa è la prima soluzione che è venuto in mente. È quindi possibile reimpostare il diff in un DF per la presentazione.

+0

Mi piace. Ma come si fa a riempire il differenziale di risultati in un nuovo DF? – eezis

+0

@eezis In questo caso: 'DataFrame (lista (diff), colonne = ['Acquirente', 'Quantità'])'. Ricorda che questo non conserva gli indici del DF originale. – Shovalt

Problemi correlati