2017-06-16 127 views
2

enter image description here如何在數據幀匹配的行值的值在另一個數據幀

我想要做的就是創建一個包含在表中的所有數據的新表1與另外一個名爲列說明(值從表2)應該匹配部件號表1

我試過使用df.merge但是,它只是使Table 3超過三行。

我也試過lookup但沒有成功。 enter image description here

我用於生產上述圖像的代碼,

pd.merge(xl_csv, xl_df, on="Part Number", how="left")[['Part Number', 'Occurrence Count', 'G1 TAT_x', 'Description']] 
+0

我不知道指數是什麼。 – piRSquared

回答

2

看來需要LEFT JOIN,然後通過子集選擇列,但首先需要通過drop_duplicatesdf2刪除重複:

cols = ['Part Num','Sample','Description'] 
df = pd.merge(df1, df2.drop_duplicates('Part Num'), on='Part Num', how='left')[cols] 
print (df) 
    Part Num Sample Description 
0   1 one Desc. one 
1   2 two Desc. two 
2   3 three Desc. three 

map的另一個解決方案:

df1['Description'] = df1['Part Num'].map(df2.drop_duplicates('Part Num') 
              .set_index('Part Num')['Description']) 
print (df1) 
    Part Num Sample Description 
0   1 one Desc. one 
1   2 two Desc. two 
2   3 three Desc. three 
+0

表2實際上有兩個以上的列,但我只是想** **說明**。 –

+0

查看我的更新,'merge'將**零件編號**展開成多行。 –

+0

是的,你有重複的問題。所以需要冷杉刪除它們。 – jezrael

相關問題