首页 > 解决方案 > 使用python合并具有重复行的数据

问题描述

当我尝试将 SAS 代码转换为 python 时,我发现了这个问题。假设我有 2 个数据框,如下所示:

df = pd.DataFrame({"monthkey": [1, 2, 3, 4, 5]})
df2 = pd.DataFrame({"name": ['foo','foo','bar']})

我希望桌子看起来像:

monthkey name
1        foo 
2        foo 
3        foo  
4        foo  
5        foo  
1        bar  
2        bar  
3        bar  
4        bar  
5        bar  

我在下面编写了 SAS 代码以供参考,但是如何使用 python 创建结果?

proc sql;
create table want as select a.*,b.*from
df as a left join df2 as b on a.monthkey;
quit;

对此有何建议?谢谢你。

标签: pythonpandasmergesas

解决方案


你可以试试下面的

df.assign(foo=1).merge(df2.drop_duplicates().assign(foo=1) ).drop('foo', 1)

推荐阅读