2017-06-27 1 views
1

Ich bin ziemlich neu zu Pandas Datenrahmen, und ich habe Probleme, zwei Tabellen zu verbinden.Registriert Pandas Datenrahmen basierend auf Spaltenwerten

Die erste df hat nur drei Spalten:

DF1: 
item_id position document_id 
336  1   10 
337  2   10 
338  3   10 
1001  1   11 
1002  2   11 
1003  3   11 
38   10   146 

Und der zweite hat genau die gleichen zwei Säulen (und viele andere):

DF2 
item_id document_id col1 col2 col3 ... 
337  10    ...  ... ... 
1002  11    ...  ... ... 
1003  11    ...  ... ... 

Was ich brauche, ist eine Operation auszuführen, die , in SQL, würde wie folgt aussehen:

DF1 join DF2 on 
DF1.document_id = DF2.document_id 
and 
DF1.item_id = DF2.item_id 

Und als Ergebnis, ich will DF2 sehen, ergänzt w i-Spalte 'Position':

item_id document_id position col1 col2 col3 ... 

Was ist ein guter Weg, dies mit Pandas zu tun?

Vielen Dank!

Antwort

2

Ich glaube, Sie brauchen merge mit inner Standard beitreten, aber ist notwendig, keine doppelten Kombinationen von Werten in beiden Spalten:

print (df2) 
    item_id document_id col1 col2 col3 
0  337   10 s  4  7 
1  1002   11 d  5  8 
2  1003   11 f  7  0 

df = pd.merge(df1, df2, on=['document_id','item_id']) 
print (df) 
    item_id position document_id col1 col2 col3 
0  337   2   10 s  4  7 
1  1002   2   11 d  5  8 
2  1003   3   11 f  7  0 

Aber wenn nötig position Spalte in Position 3:

df = pd.merge(df2, df1, on=['document_id','item_id']) 
cols = df.columns.tolist() 
df = df[cols[:2] + cols[-1:] + cols[2:-1]] 
print (df) 
    item_id document_id position col1 col2 col3 
0  337   10   2 s  4  7 
1  1002   11   2 d  5  8 
2  1003   11   3 f  7  0 
+1

Danke so sehr! So einfach und so elegant :) Das hat das Problem total gelöst. – fremorie

Verwandte Themen