2017-06-27 16 views
1

私はパンダのデータフレームが新しく、2つのテーブルを結合する際にいくつか問題が発生しています。列の値に基づいてパンダのデータフレームに結合する

最初のDFはわずか3の列があります。

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 

をそして第​​二には、まったく同じ2列(および他の多くを)持っている:

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

私は必要なものどの操作を実行することです結果として、私はwを補完し、DF2を見たいと思って、

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

をそして:、SQLで、次のようになります列の「位置」:

item_id document_id position col1 col2 col3 ... 

パンダを使用してこれを行うには、どのような方法が良いですか?

ありがとうございました!

答えて

2

は、私はあなたがデフォルトinner参加してmergeが必要だと思うが、無重複の両方の列の値の組み合わせが必要です:

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 

しかし、位置3で必要に応じてpositionコラム:

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

はありがとうそんなに!だからシンプルでエレガント:)それは完全に問題を解決した。 – fremorie

関連する問題