Pandas 基于两列匹配,将数据帧的某些列映射到另一列
我有两个数据帧,如下所示 df1: df2: 根据上面的内容,我想根据扇区、绘图匹配将Usage和Type列从df2添加到df1 预期产出:Pandas 基于两列匹配,将数据帧的某些列映射到另一列,pandas,pandas-groupby,Pandas,Pandas Groupby,我有两个数据帧,如下所示 df1: df2: 根据上面的内容,我想根据扇区、绘图匹配将Usage和Type列从df2添加到df1 预期产出: Sector Plot Price Count Usage Type A 1 250 2 R Land A 2 100 1 C Villa A 3 250
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')
添加,因为在第二个数据帧中重复:
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
添加,因为在第二个数据帧中重复:
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
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