【问题标题】:SQL style conditional joins in pandasPandas 中的 SQL 样式条件连接
【发布时间】: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。

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:
In [92]: d1.merge(d2.assign(year=d2.year+1, prior_yr_score=d2.score).drop('score',1), left_on=['ID','year'], right_on=['id_num','year'])
Out[92]:
   ID  year notes  score  id_num  prior_yr_score
0  12  2015  text   15.1      12            12.9

【讨论】:

    【解决方案2】:

    您是否可以在 df2 中添加一个执行 year+1 计算的列,然后在该新列上合并?

    【讨论】:

    • 当然 - 但我正在寻找一种在单个语句中执行此操作的方法。
    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 2017-04-20
    • 2019-05-14
    • 2023-04-07
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多