[Python] Use pandas merge_asof to achieve inexact left join

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I have two pandas series:

    right_series

    Index​
    Value
    1​
    0.1
    2​
    0.2
    3​
    0.3
    6​
    0.6
    7​
    0.7​

    left_series

    Index​
    Value
    1​
    0.1
    5​
    0.5
    10​
    1.0​

    I would like to join right_series on left_series by the indices, such that if an exact match of the index is not found, the nearest value is matched and the join behaves like a left join. Using pandas merge_asof in the following way

    result = pd.merge_asof(left=left_series,right=right_series,left_index=True,right_index=True,direction="nearest")


    yields

    Left Index​
    Left Value​
    Right Value
    1​
    0.1​
    0.1
    5​
    0.5​
    0.6
    10​
    1.0​
    0.7​

    but I would like the lines with with right index 2 & 3 to also be matched (left index 2 to right index 1 and left index 3 to right index 1 or 5) and returned in the result, e.g.,

    Left Index​
    Left Value​
    Right Value
    1​
    0.1​
    0.1
    1​
    0.1​
    0.2
    1​
    0.1​
    0.3
    5​
    0.5​
    0.6
    10​
    1.0​
    0.7​

    How can I best achieve this result?

    Continue reading...

Compartilhe esta Página