2017-06-16 133 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

相关问题