我有两个数据框,如下图所示
df1:
Sector Plot Price Count
A 1 250 2
A 2 100 1
A 3 250 3
df2:
Sector Plot Usage Type
A 1 R Land
A 1 R Land
A 2 C Villa
A 3 R Plot
A 3 R Plot
A 3 R Plot
根据上面的内容,我想根据扇区,图匹配将df2的“用法和类型”列添加到df1。
预期输出:
Sector Plot Price Count Usage Type
A 1 250 2 R Land
A 2 100 1 C Villa
A 3 250 3 R Plot
我尝试了以下代码
df3 = pd.merge(df1, df2, left_on = ['Sector', 'Plot'],
right_on = ['Sector', 'Plot'], how = 'inner')
答案 0 :(得分:4)
添加DataFrame.drop_duplicates
是因为第二个DataFrame
中有重复项:
df3 = pd.merge(df1,
df2.drop_duplicates(['Sector', 'Plot']),
on = ['Sector', 'Plot'])
print (df3)
Sector Plot Price Count Usage Type
0 A 1 250 2 R Land
1 A 2 100 1 C Villa
2 A 3 250 3 R Plot