【发布时间】:2017-12-01 07:01:53
【问题描述】:
我有 2 个像这样的 dfs
df1:
ID year notes score
12 2015 text 15.1
54 2014 text 18.4
df2:
id_num year score
12 2015 15.1
12 2014 12.9
54 2014 18.4
我正在尝试使用来自 df1 的所有数据和来自 df 的分数列创建一个新的 df,其中 df1.year = df2.year+1。像这样:
ID year notes score prior_yr_score
12 2015 text 15.1 12.9
我正在阅读 pandas 文档,但没有找到一种方法来执行这种类型的条件连接。在sql中我可以做
select a.*, b.score as prior_yr_score
from df1 as a left join df2 as b
on a.ID=b.id_num and a.year = b.year+1
而在python中我被困在
merged=pd.merge(df1, df2, how='left',left_on='ID',right_on='id_num')
如何在单个语句中执行此操作(pd.merge 或其他)?
编辑:我已经阅读了其他一些关于 python 中的 sql 样式连接的文章和文档,但还没有找到明确的答案。例如,this post 看起来很相似,但在答案中,OP 似乎实际上是在尝试按条件按组计算聚合度量,而不是在条件下加入 2 个 dfs。
【问题讨论】:
-
@AndrewL - 那篇文章似乎更多地是关于计算一个组的聚合度量。虽然也许我误读了该帖子的答案
标签: python python-3.x pandas