【问题标题】:Pandas join and fill with last occurrence [duplicate]熊猫加入并填充最后一次出现[重复]
【发布时间】:2021-12-09 00:08:45
【问题描述】:

我有以下数据框:

DF1:

key | col1 | col2
 1     13     a
 1     15     b
 1     18     c
...   ...    ...

DF2:

key | col1
 1     14
 1     15
 1     19
...

我想用DF1 中的col2 填充DF2,方法是使用以下键:["key", "col1"]。如果DF1.col1DF2.col1 没有匹配项,我想在DF1.col1 中找到小于DF2.col1 的最后一个匹配项。

所以期望的输出是:

DF2:

key | col1 | col2
 1     14     a # Not exact match, so it will take DF1.col1 = 13
 1     15     b
 1     19     c # Not exact match, so it will take DF1.col1 = 18
...   ...    ...

如果不匹配,则使用传统的 pandas 合并返回 None:

result = pd.merge(DF1, DF2, how="right", on=["key", "col1"])

结果:

key | col1 | col2
 1     14    None
 1     15     b
 1     19    None
...   ...    ...

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以使用pd.merge_asof:

    print (pd.merge_asof(df2, df1, on="col1", by="key"))
    
       key  col1 col2
    0    1    14    a
    1    1    15    b
    2    1    19    c
    

    请注意,这需要对两个 dfs 上的 col1 进行排序。

    【讨论】:

    • 这里的输出不是想要的结果而是DF1的副本
    • 你是对的,交换df2df1,你应该得到你的结果。
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2019-01-02
    • 2022-01-23
    • 2021-12-12
    相关资源
    最近更新 更多