python - 合并 2 个数据帧的不同值的相同输出

标签 python pandas merge

我正在测试以下数据帧的合并:

enter image description here

enter image description here

从下面的代码行:

merge1 = pd.merge(df1,df2,on='HPI',how='inner')

我期望这个输出:

enter image description here

但是我有:

enter image description here

此外,无论我在参数('inner','outer','left','right')中使用哪个选项,我总是得到相同的输出。 可以肯定的是,我不会根据参数如何正确合并。有人可以解释一下为什么我对所有选项都得到相同的输出吗?

最佳答案

HPI 列中存在重复项问题。可以通过set_index创建MultiIndexconcat :

merge1 = pd.concat([df1.set_index('HPI', append=True), 
                    df2.set_index('HPI', append=True)], axis=1).reset_index(level=1)

print (merge1)
      HPI  Int_rate  US_GDP_Thousands  Low_tier_HPI  Unemployment
2001   80         2                50            50             7
2002   85         3                55            52             8
2003   88         2                65            50             9
2004   85         2                55            53             6

或者reset_index对于 indexmerge 中的列按 2 列:

merge1 = pd.merge(df1.reset_index(),df2.reset_index(),on=['index','HPI'])
print (merge1)
   index  HPI  Int_rate  US_GDP_Thousands  Low_tier_HPI  Unemployment
0   2001   80         2                50            50             7
1   2002   85         3                55            52             8
2   2003   88         2                65            50             9
3   2004   85         2                55            53             6

如果可能的话,最后一个解决方案索引值也会重复:

df1 = df1.assign(new=df1.groupby('HPI').cumcount())
df2 = df2.assign(new=df2.groupby('HPI').cumcount())

merge1 = pd.merge(df1,df2,on=['new','HPI']).drop('new',axis=1)
print (merge1)
   HPI  Int_rate  US_GDP_Thousands  Low_tier_HPI  Unemployment
0   80         2                50            50             7
1   85         3                55            52             8
2   88         2                65            50             9
3   85         2                55            53             6

关于python - 合并 2 个数据帧的不同值的相同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49486674/

相关文章:

python - 在 python 中声明 "MUL key"字段。 (django 框架)

python - 如何使用 . Between 函数将对象分配给列

sql-server - 如何优化运行数百万条记录的 SQL Server Merge 语句

sql - SQL合并两个不同表的数据

image - 将 gif 图像与 png 图像合并

python - 尝试在图中查找组件时出现运行时错误

python - 是否有 django 应用程序为服务器上的文件提供文件选择器?

python - 将查询集数据传递给另一个查询 django

python plotly : box plot using column in dataframe

python - pandas 在 groupby sum 之后对每组内的值进行排序,并在使用 cumsum 后获取值的百分比