python - 使用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;
对此有何建议?谢谢你。
解决方案
你可以试试下面的
df.assign(foo=1).merge(df2.drop_duplicates().assign(foo=1) ).drop('foo', 1)
推荐阅读
- c++ - 如何解决这个前向类声明问题?
- azure-devops - 根据 AzureDevOps CI Pipeline 中的分支更改变量值
- javascript - 当不确定 JSdocs 时该放什么 @return
- python - Pandas 在单元格中添加值时不返回正确的数字
- c# - 如何更改 ListView 行的背景颜色?
- ios - 在没有通知的情况下获取当前键盘状态
- mongodb - Mongodb 使用带有嵌套数组的 $filter
- laravel - 通过 laravel 集合格式化数据集
- python-3.x - 如何编写通用的“验证”方法来接收各种输入
- ios - RxSwift:点击一个按钮用 Alamofire 发出请求,如何使它工作?